seqparse 2.0.0rc1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
seqparse/sequences.py ADDED
@@ -0,0 +1,1288 @@
1
+ """Sequence-related data structures utilized by the Seqparse module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import array
6
+ import bisect
7
+ from collections.abc import Iterable, Iterator, MutableSequence, MutableSet
8
+ import itertools
9
+ import operator
10
+ import os
11
+ from typing import Any, overload, SupportsInt, TypeAlias
12
+
13
+ import seqparse
14
+ from seqparse import regex
15
+
16
+ __all__ = ("FileSequence", "FrameChunk", "FrameSequence", "SeqparsePadError")
17
+
18
+ # Anything a FrameSequence accepts as frames: a frame number (int or digit
19
+ # string), a frame sequence string, a FrameChunk/FrameSequence, or an iterable
20
+ # of frames.
21
+ Frames: TypeAlias = str | SupportsInt | Iterable[Any]
22
+
23
+
24
+ def _is_iterable(value: object) -> bool:
25
+ """Whether value is a non-string iterable (list, set, range, ...)."""
26
+ if isinstance(value, (str, bytes)):
27
+ return False
28
+ try:
29
+ iter(value) # type: ignore[call-overload]
30
+ except TypeError:
31
+ return False
32
+ return True
33
+
34
+
35
+ def _frame_number(item: Any) -> int:
36
+ """The integer frame number of item (raises like int() on bad input)."""
37
+ return int(item)
38
+
39
+
40
+ # Frames are stored as a sorted array of 64-bit ints (8 bytes per frame, no
41
+ # int objects); frame numbers too big for that fall back to a list.
42
+ FrameStore: TypeAlias = MutableSequence[int]
43
+
44
+ # Up to this many pending frames are merged by binary-search insertion;
45
+ # more are merged by a full sort.
46
+ _SMALL_MERGE = 32
47
+
48
+
49
+ def _compact(values: list[int]) -> FrameStore:
50
+ """Store sorted, unique frames as compactly as their size allows."""
51
+ try:
52
+ return array.array("q", values)
53
+ except OverflowError:
54
+ return values
55
+
56
+
57
+ def _exact_frame(value: object) -> int | None:
58
+ """value as a frame number if it is exactly one (1.0 is; 1.5 isn't)."""
59
+ try:
60
+ number = _frame_number(value)
61
+ except (TypeError, ValueError):
62
+ return None
63
+ return number if number == value else None
64
+
65
+
66
+ def _is_correctly_padded(value: str, pad: int) -> bool:
67
+ """
68
+ Whether a string frame is correctly zero-padded for the given padding.
69
+
70
+ A frame with leading zeros must be exactly `pad` digits long; a frame with
71
+ no leading zeros may be as long as (or longer than) `pad`.
72
+ """
73
+ if value.startswith("0"):
74
+ return len(value) == pad
75
+ return len(value) >= pad
76
+
77
+
78
+ ###############################################################################
79
+ # Class: SeqparsePadError
80
+
81
+
82
+ class SeqparsePadError(ValueError):
83
+ """
84
+ Exception thrown when unexpected frame padding is encountered.
85
+
86
+ Subclasses ValueError: incorrect padding is an invalid value, and callers
87
+ catching ValueError for bad frame input should catch this too.
88
+ """
89
+
90
+
91
+ ###############################################################################
92
+ # Class: FrameChunk
93
+
94
+
95
+ class FrameChunk:
96
+ """
97
+ Representative for chunks of frames in a FrameSequence.
98
+
99
+ Args:
100
+ first (int): First frame of the chunk.
101
+ last (int, optional): Last frame of the chunk. Defaults to first
102
+ frame if not specified.
103
+ step (int, optional): Step size for the chunk. Defaults to 1.
104
+ pad (int, optional): Frame padding for the chunk. Defaults to 1.
105
+ """
106
+
107
+ # __dict__ and __weakref__ keep custom attributes and weak references
108
+ # working (the dict is only created if used).
109
+ __slots__ = (
110
+ "__dict__",
111
+ "__weakref__",
112
+ "_first",
113
+ "_last",
114
+ "_length",
115
+ "_output",
116
+ "_pad",
117
+ "_step",
118
+ )
119
+
120
+ _first: int
121
+ _last: int
122
+ _length: int
123
+ _output: str
124
+ _pad: int
125
+ _step: int
126
+
127
+ # Mutable, and equality depends on mutable state: deliberately
128
+ # unhashable (like set and dict).
129
+ __hash__ = None # type: ignore[assignment]
130
+
131
+ def __init__(
132
+ self,
133
+ first: SupportsInt | str,
134
+ last: SupportsInt | str | None = None,
135
+ step: SupportsInt | str | None = 1,
136
+ pad: SupportsInt | str = 1,
137
+ ) -> None:
138
+ """Initialise the instance."""
139
+ self._pad = int(pad)
140
+ # This will calculate the string output as well!
141
+ self.set_frames(first, last, step)
142
+
143
+ def __setstate__(self, state: Any) -> None:
144
+ """Unpickle, including pickles made by seqparse 1.0.x."""
145
+ if isinstance(state, tuple):
146
+ seqparse.restore_slots(self, state)
147
+ return
148
+ data = state["_data"] # 1.0.x kept its state in plain dicts
149
+ self._first, self._last = data["first"], data["last"]
150
+ self._length, self._pad, self._step = (
151
+ data["length"],
152
+ data["pad"],
153
+ data["step"],
154
+ )
155
+ self._output = state["_output"]
156
+
157
+ def __contains__(self, item: object) -> bool:
158
+ """Whether the chunk contains the specified (non-)padded frame."""
159
+ frame_num = _frame_number(item)
160
+ if not self._first <= frame_num <= self._last:
161
+ return False
162
+ if (frame_num - self._first) % self.step:
163
+ return False
164
+ if isinstance(item, str):
165
+ return _is_correctly_padded(item, self._pad)
166
+ return True
167
+
168
+ def __eq__(self, other: object) -> bool:
169
+ """Define equality between instances."""
170
+ if isinstance(other, FrameChunk) and type(other) is type(self):
171
+ return self._key() == other._key()
172
+ return False
173
+
174
+ def __iter__(self) -> Iterator[str]:
175
+ """Iterate over the frames contained by the chunk."""
176
+ spec = f"0{self._pad}d"
177
+ for frame in range(self._first, self._last + 1, self.step):
178
+ yield format(frame, spec)
179
+
180
+ def __len__(self) -> int:
181
+ """Return the length of the frame chunk."""
182
+ return self._length
183
+
184
+ def __repr__(self) -> str: # pragma: no cover
185
+ """Pretty representation of the instance."""
186
+ return (
187
+ f"{type(self).__name__}(first={self._first}, last={self._last}, "
188
+ f"step={self._step}, length={self._length}, pad={self._pad})"
189
+ )
190
+
191
+ def __reversed__(self) -> Iterator[str]:
192
+ """Allow reversed iteration via reversed()."""
193
+ spec = f"0{self._pad}d"
194
+ for frame in reversed(range(self._first, self._last + 1, self.step)):
195
+ yield format(frame, spec)
196
+
197
+ def __str__(self) -> str:
198
+ """String representation of the frame chunk."""
199
+ return self._output
200
+
201
+ def _key(self) -> tuple[int, int, int, int, int]:
202
+ """Everything equality depends on."""
203
+ return (self._first, self._last, self._length, self._pad, self._step)
204
+
205
+ @property
206
+ def first(self) -> int:
207
+ """int: first frame of the chunk."""
208
+ return self._first
209
+
210
+ @property
211
+ def last(self) -> int:
212
+ """int: Last frame of the chunk."""
213
+ return self._last
214
+
215
+ @property
216
+ def pad(self) -> int:
217
+ """int: zero-padding for the frames contained by the object."""
218
+ return self._pad
219
+
220
+ @property
221
+ def step(self) -> int:
222
+ """int: step size for the frame chunk."""
223
+ return max(self._step, 1)
224
+
225
+ def invert(
226
+ self, first: int | None = None, last: int | None = None
227
+ ) -> FrameSequence:
228
+ """
229
+ Calculate iterator for the frames missing from the chunk.
230
+
231
+ Args:
232
+ first (int, optional): First frame of the range that you'd like to
233
+ invert. Defaults to first frame of the chunk if not specified.
234
+ last (int, optional): Last frame of the range that you'd like to
235
+ invert. Defaults to last frame of the chunk if not specified.
236
+
237
+ Returns:
238
+ FrameSequence instance containing the missing frames (if any).
239
+
240
+ Examples:
241
+ >>> from seqparse.sequences import FrameChunk
242
+ >>> chunk = FrameChunk(first=5, last=11, step=2, pad=3)
243
+ >>> print(chunk)
244
+ 005-011x2
245
+ >>> inverted = chunk.invert()
246
+ >>> print(inverted)
247
+ 006-010x2
248
+ >>> print(repr(inverted))
249
+ FrameSequence(pad=3, frames=set([6, 8, 10]))
250
+ >>> print(chunk.invert(first=1))
251
+ 001-004,006-010x2
252
+ >>> print(chunk.invert(last=15))
253
+ 006-012x2,013-015
254
+ >>> print(chunk.invert(first=1, last=15))
255
+ 001-004,006-012x2,013-015
256
+ """
257
+ if first is None:
258
+ first = self._first
259
+ if last is None:
260
+ last = self._last
261
+
262
+ missing = set(range(first, last + 1))
263
+ missing.difference_update(range(self._first, self._last + 1, self.step))
264
+ inverted = FrameSequence(pad=self._pad)
265
+ inverted._frames = _compact(sorted(missing))
266
+ return inverted
267
+
268
+ def set_frames(
269
+ self,
270
+ first: SupportsInt | str,
271
+ last: SupportsInt | str | None = None,
272
+ step: SupportsInt | str | None = 1,
273
+ ) -> str:
274
+ """
275
+ Set and validate the first and last frames of the chunk.
276
+
277
+ Args:
278
+ first (int): First frame of the chunk.
279
+ last (int, optional): Last frame of the chunk. Defaults to first
280
+ frame if not specified.
281
+ step (int, optional): Step size for the chunk. Defaults to 1.
282
+
283
+ Returns:
284
+ str representation of the frame chunk.
285
+ """
286
+ if last is None:
287
+ last = first
288
+
289
+ low = int(first)
290
+ high = int(last)
291
+ size = max(1, int(step or 1))
292
+
293
+ if high < low:
294
+ raise ValueError(
295
+ f"Last frame is less than first frame: {high:d} < {low:d}"
296
+ )
297
+
298
+ # Calculate the length and the real last frame of the chunk.
299
+ bits = (high - low) // size
300
+ high = low + bits * size
301
+ size = min(high - low, size)
302
+
303
+ # Calculate the string representation of the frame chunk.
304
+ spec = f"0{self._pad}d"
305
+ output = format(low, spec)
306
+ if bits == 1:
307
+ output += "," + format(high, spec)
308
+ elif bits > 1:
309
+ output += "-" + format(high, spec)
310
+ if size > 1 and bits > 1:
311
+ output += f"x{size:d}"
312
+
313
+ self._first, self._last, self._step = low, high, size
314
+ self._length = 1 + bits
315
+ self._output = output
316
+ return output
317
+
318
+
319
+ ###############################################################################
320
+ # Class: FrameSequence
321
+
322
+
323
+ class FrameSequence(MutableSet[str], regex.SeqparseRegexMixin):
324
+ """
325
+ Representative for zero-padded frame sequences.
326
+
327
+ Args:
328
+ frames (many types, optional): Initial frame range to store in the
329
+ instance. Acceptable input types include FrameChunk, FrameSequence
330
+ instances, string representation of a frame sequence, list, set, or
331
+ tuple of integer frames.
332
+ pad (int, optional): Initial zero-padding for the instance. Ignored
333
+ if input iterable is a either a FrameChunk, FrameSequence, or
334
+ string representation of a frame sequence.
335
+
336
+ Examples:
337
+ All of the following will result in equivalent output:
338
+
339
+ >>> FrameSequence(range(1,6), pad=4)
340
+ >>> FrameSequence(set([1, 2, 3, 4, 5]), pad=4)
341
+ >>> FrameSequence("0001-0005")
342
+ >>> FrameSequence(FrameChunk(first=1, last=5, pad=4))
343
+ """
344
+
345
+ # __dict__ and __weakref__ keep custom attributes and weak references
346
+ # working (the dict is only created if used).
347
+ __slots__ = (
348
+ "__dict__",
349
+ "__weakref__",
350
+ "_dirty",
351
+ "_frames",
352
+ "_is_padded",
353
+ "_ordered",
354
+ "_output",
355
+ "_pad",
356
+ "_pending",
357
+ )
358
+
359
+ def __init__(
360
+ self, frames: Frames | None = None, pad: SupportsInt | None = 1
361
+ ) -> None:
362
+ """Initialise the instance."""
363
+ super().__init__()
364
+
365
+ # Sorted, unique frames, plus frames added since the last _sync()
366
+ # (unsorted, possibly duplicated or already present).
367
+ self._frames: FrameStore = array.array("q")
368
+ self._pending: FrameStore = array.array("q")
369
+ # Whether _pending is strictly increasing.
370
+ self._ordered = True
371
+ self._dirty = True
372
+ self._is_padded = False
373
+ self._output = ""
374
+ # 0 means "not set yet": a frame sequence string sets it from its
375
+ # first frame.
376
+ self._pad = 0
377
+
378
+ if isinstance(frames, str):
379
+ if not self.is_frame_sequence(frames):
380
+ raise ValueError(
381
+ f"Invalid iterable specified ({type(frames)}, {frames!r})"
382
+ )
383
+ self._add_frame_sequence(frames)
384
+ return
385
+
386
+ if isinstance(frames, (FrameChunk, FrameSequence)):
387
+ pad = frames.pad
388
+ elif frames is None:
389
+ frames = []
390
+ elif not _is_iterable(frames):
391
+ frames = [frames]
392
+
393
+ self.pad = pad
394
+ self._add_from_iterable(frames) # type: ignore[arg-type]
395
+
396
+ def __setstate__(self, state: Any) -> None:
397
+ """Unpickle, including pickles made by seqparse 1.0.x."""
398
+ if isinstance(state, tuple):
399
+ seqparse.restore_slots(self, state)
400
+ else:
401
+ self._set_legacy_state(state)
402
+
403
+ def _set_legacy_state(self, state: dict[str, Any]) -> None:
404
+ """Restore the plain-dict state that seqparse 1.0.x pickled."""
405
+ self._frames = _compact(sorted(state["_data"]))
406
+ self._pending = array.array("q")
407
+ self._ordered = True
408
+ self._dirty = True
409
+ self._is_padded = False
410
+ self._output = ""
411
+ self.pad = state["_attrs"]["pad"]
412
+
413
+ def __contains__(self, item: object) -> bool:
414
+ """Defining containment logic (per standard set)."""
415
+ if self._has(_frame_number(item)):
416
+ if isinstance(item, str):
417
+ return _is_correctly_padded(item, self._pad)
418
+ return True
419
+
420
+ return False
421
+
422
+ def __iter__(self) -> Iterator[str]:
423
+ """Defining item iteration logic (per standard set)."""
424
+ if self._dirty:
425
+ self.calculate()
426
+
427
+ spec = f"0{self._pad}d"
428
+ # Iterate a copy, so changing the sequence mid-loop is safe.
429
+ for frame in self._frames[:]:
430
+ yield format(frame, spec)
431
+
432
+ def __len__(self) -> int:
433
+ """Defining item length logic (per standard set)."""
434
+ self._sync()
435
+ return len(self._frames)
436
+
437
+ def __repr__(self) -> str: # pragma: no cover
438
+ """Pretty representation of the instance."""
439
+ return (
440
+ f"{type(self).__name__}(pad={self._pad:d}, "
441
+ f"frames=set({self._sorted_frames()!r}))"
442
+ )
443
+
444
+ def __reversed__(self) -> Iterator[str]:
445
+ """Allow reversed iteration via reversed()."""
446
+ return reversed(list(self))
447
+
448
+ def __str__(self) -> str:
449
+ """String reprentation of the frame sequence."""
450
+ self.calculate()
451
+ return self._output
452
+
453
+ @property
454
+ def is_dirty(self) -> bool:
455
+ """bool: Whether output needs to be recalculated after an update."""
456
+ return self._dirty
457
+
458
+ @property
459
+ def is_padded(self) -> bool:
460
+ """bool: Whether the FrameSequence contains any zero-padded frames."""
461
+ self.calculate()
462
+ return self._is_padded
463
+
464
+ @property
465
+ def pad(self) -> int:
466
+ """
467
+ int: Zero-padding for the frames contained by the object.
468
+
469
+ Minimum acceptable value for pad is 1.
470
+ """
471
+ return self._pad
472
+
473
+ @pad.setter
474
+ def pad(self, val: SupportsInt | None) -> None:
475
+ self._pad = max(1, int(val or 1))
476
+ self._dirty = True # the output's padding changes
477
+
478
+ def add(self, value: Frames) -> None:
479
+ """Defining value addition logic (per standard set)."""
480
+ if type(value) is int:
481
+ self._push(value)
482
+
483
+ elif isinstance(value, str):
484
+ # isdecimal() accepts exactly the digits the frame regex's \d
485
+ # does, so a single frame skips the regex entirely.
486
+ if value.isdecimal():
487
+ self._check_pad(value, strict=False)
488
+ self._push(int(value))
489
+ elif self.is_frame_sequence(value):
490
+ self._add_frame_sequence(value)
491
+ return
492
+ else:
493
+ raise ValueError(f"Invalid value specified ({value!r})")
494
+
495
+ elif isinstance(value, (FrameChunk, FrameSequence)):
496
+ if value.pad != self._pad:
497
+ raise SeqparsePadError(
498
+ f"Specified value ({value!r}) is incorrectly padded "
499
+ f"({value.pad:d} != {self._pad:d})"
500
+ )
501
+ # Same pad, so every frame is valid: add the integers directly.
502
+ # (FileSequence iterates file names, so it keeps the slow path.)
503
+ if type(value) is FrameChunk:
504
+ self._extend(
505
+ range(value.first, value.last + 1, value.step), True
506
+ )
507
+ elif type(value) is FrameSequence:
508
+ value._sync()
509
+ self._extend(value._frames, True)
510
+ else:
511
+ self._add_from_iterable(value)
512
+
513
+ elif _is_iterable(value):
514
+ self._add_from_iterable(value) # type: ignore[arg-type]
515
+
516
+ else:
517
+ self._push(_frame_number(value))
518
+
519
+ self._dirty = True
520
+
521
+ def discard(self, value: SupportsInt | str) -> None:
522
+ """Defining item discard logic (per standard set)."""
523
+ if isinstance(value, str):
524
+ self._check_pad(value, strict=False)
525
+ number: int | None = int(value)
526
+ else:
527
+ number = _exact_frame(value)
528
+ self._dirty = True
529
+ if number is None:
530
+ return # not a frame number (eg 1.5), so not in the sequence
531
+
532
+ self._sync()
533
+ frames = self._frames
534
+ idx = bisect.bisect_left(frames, number)
535
+ if idx < len(frames) and frames[idx] == number:
536
+ del frames[idx]
537
+
538
+ def update(self, value: Iterable[Any]) -> None:
539
+ """Defining value update logic (per standard set)."""
540
+ for item in value:
541
+ self.add(item)
542
+
543
+ def calculate(self, force: bool = False) -> None:
544
+ """
545
+ Calculate the output file sequence.
546
+
547
+ Output string file sequence will always be recalculated if the instance
548
+ has been marked as "dirty" when its contents have been modified by an
549
+ external process.
550
+
551
+ Args:
552
+ force (bool, optional): Whether to force recalculation.
553
+
554
+ Returns:
555
+ None
556
+ """
557
+ if not (self._dirty or force):
558
+ return
559
+
560
+ self._sync()
561
+ self._is_padded = False
562
+ self._output = ""
563
+ frames = self._frames
564
+ num_frames = len(frames)
565
+ if not num_frames:
566
+ return
567
+
568
+ spec = f"0{self._pad}d"
569
+ parts: list[str] = []
570
+
571
+ def emit(first: int, last: int, length: int, step: int) -> None:
572
+ """Render the run frames[first..last] (indices)."""
573
+ low, high = format(frames[first], spec), format(frames[last], spec)
574
+ if length == 1:
575
+ parts.append(low)
576
+ elif length == 2: # noqa: PLR2004 - a pair is written "a,b"
577
+ parts.append(f"{low},{high}")
578
+ elif step > 1:
579
+ parts.append(f"{low}-{high}x{step}")
580
+ else:
581
+ parts.append(f"{low}-{high}")
582
+
583
+ # Split the sorted frames into runs with a constant step. A run of
584
+ # exactly two frames followed by a different step gives up its second
585
+ # frame to the next run, so [1, 3, 4, 5] renders as "1,3-5" rather
586
+ # than "1,3,4,5".
587
+ start, step = 0, 0
588
+ for idx, gap in enumerate(
589
+ map(operator.sub, itertools.islice(frames, 1, None), frames)
590
+ ):
591
+ if not step:
592
+ step = gap
593
+ elif gap != step:
594
+ if idx - start == 1:
595
+ emit(start, start, 1, 1)
596
+ start, step = idx, gap
597
+ else:
598
+ emit(start, idx, idx - start + 1, step)
599
+ start, step = idx + 1, 0
600
+ emit(start, num_frames - 1, num_frames - start, step)
601
+
602
+ # This will be used by the parent FileExtension instance during the
603
+ # zero-pad consolidation stage of the output process.
604
+ self._is_padded = frames[0] < 10 ** (self._pad - 1)
605
+ self._output = ",".join(parts)
606
+ self._dirty = False
607
+
608
+ def invert(self) -> FrameSequence:
609
+ """
610
+ Calculate frames missing from the sequence.
611
+
612
+ Returns:
613
+ FrameSequence containing the missing frames (if any).
614
+ """
615
+ self._sync()
616
+ inverted = FrameSequence(pad=self._pad)
617
+ # Gaps between consecutive sorted frames are already sorted and
618
+ # unique, so they go straight into the store (same kind as ours, so
619
+ # anything that fits ours fits it).
620
+ missing = self._frames[:0]
621
+ for low, high in itertools.pairwise(self._frames):
622
+ if high - low > 1:
623
+ missing.extend(range(low + 1, high))
624
+ inverted._frames = missing
625
+ return inverted
626
+
627
+ def _has(self, number: int) -> bool:
628
+ """Whether the frame number is in the sequence."""
629
+ self._sync()
630
+ frames = self._frames
631
+ idx = bisect.bisect_left(frames, number)
632
+ return idx < len(frames) and frames[idx] == number
633
+
634
+ def _sorted_frames(self) -> list[int]:
635
+ """The frame numbers, sorted."""
636
+ self._sync()
637
+ return list(self._frames)
638
+
639
+ def _push(self, number: int) -> None:
640
+ """Queue one frame number for addition."""
641
+ pending = self._pending
642
+ if pending and number <= pending[-1]:
643
+ self._ordered = False
644
+ try:
645
+ pending.append(number)
646
+ except OverflowError:
647
+ self._pending = pending = list(pending)
648
+ pending.append(number)
649
+
650
+ def _extend(self, numbers: Iterable[int], ordered: bool = False) -> None:
651
+ """
652
+ Queue frame numbers for addition.
653
+
654
+ Args:
655
+ numbers (iterable of int): Frame numbers to add.
656
+ ordered (bool, optional): Whether numbers is strictly increasing.
657
+ """
658
+ pending = self._pending
659
+ if ordered and pending:
660
+ first = next(iter(numbers), None)
661
+ ordered = first is None or first > pending[-1]
662
+ if not ordered:
663
+ self._ordered = False
664
+ try:
665
+ pending.extend(numbers)
666
+ except OverflowError:
667
+ # Some numbers may already be in: duplicates are harmless.
668
+ self._ordered = False
669
+ self._pending = pending = list(pending)
670
+ pending.extend(numbers)
671
+ self._dirty = True
672
+
673
+ def _sync(self) -> None:
674
+ """Merge pending frames into the sorted, unique frame store."""
675
+ pending = self._pending
676
+ if not pending:
677
+ return
678
+ frames = self._frames
679
+ ordered = self._ordered
680
+ self._pending = array.array("q")
681
+ self._ordered = True
682
+ try:
683
+ if ordered and (not frames or frames[-1] < pending[0]):
684
+ frames.extend(pending)
685
+ return
686
+ if len(pending) <= _SMALL_MERGE:
687
+ for number in pending:
688
+ idx = bisect.bisect_left(frames, number)
689
+ if idx == len(frames) or frames[idx] != number:
690
+ frames.insert(idx, number)
691
+ return
692
+ except OverflowError:
693
+ pass # a frame is too big for the array: rebuild below
694
+ merged = set(frames)
695
+ merged.update(pending)
696
+ self._frames = _compact(sorted(merged))
697
+
698
+ def _add_from_iterable(self, iterable: Iterable[Any]) -> None:
699
+ """
700
+ Add items from supplied iterable to the instance.
701
+
702
+ Args:
703
+ iterable (many types): Iterable (usually a list-list object) from
704
+ which you'd like to add items to the instance.
705
+
706
+ Returns:
707
+ None
708
+ """
709
+ if (
710
+ isinstance(iterable, (FrameChunk, FrameSequence))
711
+ and type(iterable) in (FrameChunk, FrameSequence)
712
+ and iterable.pad == self._pad
713
+ ):
714
+ self.add(iterable) # integer fast path, no string round trip
715
+ return
716
+ if isinstance(iterable, array.array) and iterable.typecode == "q":
717
+ self._extend(iterable)
718
+ return
719
+ if isinstance(iterable, range):
720
+ self._extend(iterable, iterable.step > 0)
721
+ return
722
+ if isinstance(iterable, (list, tuple, set, frozenset)):
723
+ # array() converts in C and rejects anything that isn't an
724
+ # integer (strings need pad checks; floats, huge ints, ...),
725
+ # which then takes the general path below.
726
+ try:
727
+ numbers = array.array("q", iterable)
728
+ except (TypeError, OverflowError):
729
+ pass
730
+ else:
731
+ # Sorted input (common) skips the merge's temporary set.
732
+ ordered = not isinstance(iterable, (set, frozenset)) and all(
733
+ map(
734
+ operator.lt, numbers, itertools.islice(numbers, 1, None)
735
+ )
736
+ )
737
+ self._extend(numbers, ordered)
738
+ return
739
+ for item in iterable:
740
+ self.add(item)
741
+
742
+ def _add_frame_sequence(self, frame_seq: str) -> None:
743
+ """
744
+ Add a string frame sequence to the instance.
745
+
746
+ Args:
747
+ frame_seq (str): frame sequence that you'd like to add to the
748
+ instance.
749
+
750
+ Returns:
751
+ None
752
+ """
753
+ # Callers have already validated frame_seq against the frame sequence
754
+ # regex, so each chunk is exactly "first[-last[xstep]]".
755
+ self._dirty = True
756
+ pending = self._pending
757
+ ordered = self._ordered
758
+ try:
759
+ for bit in frame_seq.split(","):
760
+ if not bit:
761
+ continue
762
+
763
+ first, _, rest = bit.partition("-")
764
+ last, _, step = rest.partition("x")
765
+ if not self._pad:
766
+ self.pad = len(first)
767
+
768
+ self._check_pad(first)
769
+ if last:
770
+ self._check_pad(last)
771
+
772
+ low = int(first)
773
+ high = int(last) if last else low
774
+ if high < low:
775
+ raise ValueError(
776
+ "Last frame is less than first frame: "
777
+ f"{high:d} < {low:d}"
778
+ )
779
+ frames = range(low, high + 1, max(1, int(step or 1)))
780
+ if ordered and pending and low <= pending[-1]:
781
+ ordered = False
782
+ try:
783
+ pending.extend(frames)
784
+ except OverflowError:
785
+ ordered = False
786
+ self._pending = pending = list(pending)
787
+ pending.extend(frames)
788
+ finally:
789
+ # Frames added before an error stay added (as before).
790
+ self._ordered = ordered
791
+
792
+ def _check_pad(self, value: str, strict: bool = True) -> None:
793
+ """
794
+ Raise SeqparsePadError if a string frame is incorrectly padded.
795
+
796
+ Args:
797
+ value (str): String frame to validate against the instance's pad.
798
+ strict (bool, optional): Whether to also reject frames without
799
+ leading zeros that are shorter than the pad. Defaults to True.
800
+
801
+ Returns:
802
+ None
803
+ """
804
+ if strict:
805
+ valid = _is_correctly_padded(value, self._pad)
806
+ else:
807
+ valid = not value.startswith("0") or len(value) == self._pad
808
+ if not valid:
809
+ raise SeqparsePadError(
810
+ f"Specified value ({value!r}) is incorrectly padded "
811
+ f"({len(value):d} != {self._pad:d})"
812
+ )
813
+
814
+
815
+ ###############################################################################
816
+ # Class: FileSequence
817
+
818
+
819
+ class FileSequence(FrameSequence):
820
+ """
821
+ Representative for sequences of files.
822
+
823
+ You may create a new instance of this class a couple of ways:
824
+
825
+ 1. Either clone a new instance from an existing one ...
826
+
827
+ >>> clone = FileSequence(parent)
828
+
829
+ 2. ... or create a valid instance by providing a file extension and at
830
+ least one frame (the base name is optional in every sense of the word):
831
+
832
+ >>> fseq = FileSequence(frames="0001", ext="exr")
833
+
834
+ Args:
835
+ name (str, optional): Base name (including containing directory) for
836
+ the file sequence.
837
+ frames (many types, optional): Initial frame range to store in the
838
+ instance. Acceptable input types include FrameChunk, FrameSequence
839
+ instances, string representation of a frame sequence, list, set, or
840
+ tuple of integer frames.
841
+ ext (str, optional): File extension for the sequence.
842
+ pad (int, optional): Frame padding for the sequence. Defaults to 1.
843
+ """
844
+
845
+ __slots__ = (
846
+ "_ctime",
847
+ "_ext",
848
+ "_full",
849
+ "_mtime",
850
+ "_name",
851
+ "_path",
852
+ "_size",
853
+ "_stat",
854
+ )
855
+
856
+ # Mutable, and equality depends on mutable state: deliberately
857
+ # unhashable (like set and dict).
858
+ __hash__ = None # type: ignore[assignment]
859
+
860
+ def __init__(
861
+ self,
862
+ name: FileSequence | str | None = None,
863
+ frames: Frames | None = None,
864
+ ext: str | None = None,
865
+ pad: SupportsInt | None = 1,
866
+ ) -> None:
867
+ """Initialise the instance."""
868
+ self._ctime: float | None = None
869
+ self._mtime: float | None = None
870
+ self._size: int | None = None
871
+ self._ext: str | None = None
872
+ self._full = ""
873
+ self._name: str | None = None
874
+ self._path: str | None = None
875
+ self._stat: dict[int, os.stat_result] = {}
876
+
877
+ source = None
878
+ if isinstance(name, FileSequence):
879
+ source = name
880
+ name = None
881
+ frames, ext, pad = source._sorted_frames(), source.ext, source.pad
882
+ elif name:
883
+ # Only treat the name as a complete file sequence string when no
884
+ # frames are given and any given extension agrees with it;
885
+ # otherwise base names that happen to look like file sequences
886
+ # (eg "comp.1.final") would be mangled.
887
+ file_seq_bits = None
888
+ if isinstance(name, str) and frames is None:
889
+ file_seq_bits = self.file_seq_match(name)
890
+ if file_seq_bits and ext not in (None, file_seq_bits.ext):
891
+ file_seq_bits = None
892
+ if file_seq_bits:
893
+ name, frames, ext = file_seq_bits
894
+ pad = None
895
+
896
+ if frames is None:
897
+ frames = []
898
+
899
+ super().__init__(frames, pad=pad)
900
+
901
+ self.ext = ext
902
+ if source is not None:
903
+ self.path = source.path
904
+ self.name = source.name
905
+ self._stat.update(source.stat())
906
+ else:
907
+ self.name = name
908
+
909
+ def _set_legacy_state(self, state: dict[str, Any]) -> None:
910
+ """Restore the plain-dict state that seqparse 1.0.x pickled."""
911
+ super()._set_legacy_state(state)
912
+ info = state["_info"]
913
+ self._ext, self._full = info["ext"], info["full"]
914
+ self._name, self._path = info["name"], info["path"]
915
+ self._stat = state["_stat"]
916
+ self._ctime = self._mtime = self._size = None
917
+
918
+ def __contains__(self, item: object) -> bool:
919
+ """Defining containment logic (per standard set)."""
920
+ if str(item).isdigit():
921
+ return super().__contains__(item)
922
+ if not isinstance(item, str):
923
+ return item in set(self)
924
+
925
+ # A file name is a member when it is prefix + padded frame + suffix
926
+ # for one of our frames; check that directly instead of building
927
+ # every file name.
928
+ if os.altsep: # Windows: either separator names the same file
929
+ item = item.replace(os.altsep, os.sep)
930
+ prefix, suffix = self._name_affixes()
931
+ if len(item) <= len(prefix) + len(suffix):
932
+ return False
933
+ if not (item.startswith(prefix) and item.endswith(suffix)):
934
+ return False
935
+ frame = item[len(prefix) : len(item) - len(suffix)]
936
+ digits = frame.removeprefix("-") # negative frames render as "-005"
937
+ if not (digits.isascii() and digits.isdigit()):
938
+ return False
939
+ number = int(frame)
940
+ return self._has(number) and frame == f"{number:0{self._pad}d}"
941
+
942
+ def __eq__(self, other: object) -> bool:
943
+ """Define equality between instances."""
944
+ if type(other) is type(self):
945
+ return super().__eq__(other)
946
+ return False
947
+
948
+ def __iter__(self) -> Iterator[str]:
949
+ """Defining item iteration logic (per standard set)."""
950
+ prefix, suffix = self._name_affixes()
951
+ for frame in super().__iter__():
952
+ yield f"{prefix}{frame}{suffix}"
953
+
954
+ def __repr__(self) -> str: # pragma: no cover
955
+ """Pretty representation of the instance."""
956
+ return (
957
+ f"{type(self).__name__}(full_name={self._full!r}, "
958
+ f"ext={self._ext!r}, pad={self._pad}, "
959
+ f"frames=set({self._sorted_frames()!r}))"
960
+ )
961
+
962
+ def __str__(self) -> str:
963
+ """String reprentation of the frame sequence."""
964
+ frames = super().__str__()
965
+ return self._get_sequence_output(frames)
966
+
967
+ @property
968
+ def ctime(self) -> float | None:
969
+ """
970
+ int: Most recent inode or file change time for a file in the sequence.
971
+
972
+ Returns None if the files have not been stat'd on disk.
973
+ """
974
+ self.calculate()
975
+ return self._ctime
976
+
977
+ @property
978
+ def ext(self) -> str | None:
979
+ """str: File extension for the sequence."""
980
+ return self._ext
981
+
982
+ @ext.setter
983
+ def ext(self, val: object) -> None:
984
+ self._ext = str(val) if val else None
985
+
986
+ @property
987
+ def frames(self) -> Iterator[str]:
988
+ """iterator(str): the file sequence's padded frames."""
989
+ yield from super().__iter__()
990
+
991
+ @property
992
+ def pretty_frames(self) -> str:
993
+ """str: pretty representation of the file sequence's print frames."""
994
+ return super().__str__()
995
+
996
+ @property
997
+ def full_name(self) -> str:
998
+ """str: Full name of the sequence, including containing directory."""
999
+ return self._full
1000
+
1001
+ @property
1002
+ def mtime(self) -> float | None:
1003
+ """
1004
+ int: Most recent file modification time for a file in the sequence.
1005
+
1006
+ Returns None if the files have not been stat'd on disk.
1007
+ """
1008
+ self.calculate()
1009
+ return self._mtime
1010
+
1011
+ @property
1012
+ def name(self) -> str | None:
1013
+ """
1014
+ str: Base name of the file sequence (no containing directory).
1015
+
1016
+ Note: Setting this property will modify both the `full_path` and `path`
1017
+ properties.
1018
+ """
1019
+ return self._name
1020
+
1021
+ @name.setter
1022
+ def name(self, val: object) -> None:
1023
+ self._name = None
1024
+ text = str(val) if val else ""
1025
+ if text:
1026
+ # If it's a file path (complete with directory prefix), set the
1027
+ # path property as well.
1028
+ if os.sep in text or (os.altsep and os.altsep in text):
1029
+ path_name, text = os.path.split(os.path.normpath(text))
1030
+ self.path = path_name
1031
+ self._name = text
1032
+
1033
+ self._full = os.path.join(self._path or "", text)
1034
+
1035
+ @property
1036
+ def path(self) -> str | None:
1037
+ """
1038
+ str: Directory in which the contained files are located.
1039
+
1040
+ Note: Setting the `name` property will reset the contained value.
1041
+ """
1042
+ return self._path
1043
+
1044
+ @path.setter
1045
+ def path(self, val: str | os.PathLike[str] | None) -> None:
1046
+ self._path = str(os.path.normpath(val)) if val else None
1047
+ self._full = os.path.join(self._path or "", self._name or "")
1048
+
1049
+ @property
1050
+ def size(self) -> int | None:
1051
+ """
1052
+ int: Total size of the file sequence in bytes.
1053
+
1054
+ Returns None if the files have not been stat'd on disk.
1055
+ """
1056
+ self.calculate()
1057
+ return self._size
1058
+
1059
+ def discard(self, value: SupportsInt | str) -> None:
1060
+ """Defining value discard logic (per standard set)."""
1061
+ super().discard(value)
1062
+ number = int(value) if isinstance(value, str) else _exact_frame(value)
1063
+ if number is not None:
1064
+ self._stat.pop(number, None)
1065
+
1066
+ def update(self, iterable: Iterable[Any]) -> None:
1067
+ """Defining item update logic (per standard set)."""
1068
+ if isinstance(iterable, FileSequence):
1069
+ for attr in ("ext", "full_name"):
1070
+ iterable_value = getattr(iterable, attr)
1071
+ self_value = getattr(self, attr)
1072
+ if iterable_value != self_value:
1073
+ raise ValueError(
1074
+ "Attribute mismatch on supplied FileSequence "
1075
+ f"instance ({attr}): self:{self_value!r} != "
1076
+ f"iterable:{iterable_value!r}"
1077
+ )
1078
+
1079
+ self._stat.update(iterable.stat())
1080
+ # Frames are valid for this pad unless they carry leading zeros
1081
+ # of a different width; then take the slow path (which raises).
1082
+ iterable._sync()
1083
+ other = iterable._frames
1084
+ if other and (
1085
+ iterable.pad == self._pad
1086
+ or other[0] >= 10 ** (iterable.pad - 1)
1087
+ ):
1088
+ self._extend(other, True)
1089
+ return
1090
+ iterable = iterable.frames
1091
+
1092
+ for item in iterable:
1093
+ self.add(item)
1094
+
1095
+ def cache_stat(
1096
+ self, frame: SupportsInt | str, input_stat: seqparse.StatLike
1097
+ ) -> os.stat_result:
1098
+ """
1099
+ Cache file system stat data for the specified frame.
1100
+
1101
+ Input disk stat value will be stored in a new stat_result
1102
+ instance.
1103
+
1104
+ Args:
1105
+ frame (int): Frame for which you'd like to cache the supplied stat
1106
+ data.
1107
+ input_stat (stat_result): Value that you'd like to cache.
1108
+
1109
+ Returns:
1110
+ stat_result that was successfully cached.
1111
+ """
1112
+ number = int(frame)
1113
+ self._stat[number] = seqparse.get_stat_result(input_stat)
1114
+ return self._stat[number]
1115
+
1116
+ def calculate(self, force: bool = False) -> None:
1117
+ """
1118
+ Calculate the output file sequence.
1119
+
1120
+ Output string file sequence will always be recalculated if the instance
1121
+ has been marked as "dirty" when its contents have been modified by an
1122
+ external process.
1123
+
1124
+ Args:
1125
+ force (bool, optional): Whether to force recalculation.
1126
+
1127
+ Returns:
1128
+ None
1129
+ """
1130
+ if not (self._dirty or force):
1131
+ return
1132
+
1133
+ super().calculate(force=force)
1134
+
1135
+ # Cache disk stats for easy/quick access via property ...
1136
+ self._aggregate_stats()
1137
+
1138
+ def invert(self) -> FileSequence:
1139
+ """
1140
+ Calculate file names missing from the sequence.
1141
+
1142
+ Returns:
1143
+ FileSequence containing the missing files (if any).
1144
+ """
1145
+ frames = super().invert()
1146
+ inverted = FileSequence(frames=frames, ext=self._ext, pad=frames.pad)
1147
+ inverted.path = self._path
1148
+ inverted.name = self._name
1149
+ return inverted
1150
+
1151
+ def empty_files(self) -> FileSequence:
1152
+ """
1153
+ Find the zero-byte files in the sequence.
1154
+
1155
+ Only frames whose disk stats are already cached (see `stat`) can be
1156
+ found, so scan with disk stats enabled first; a frame without cached
1157
+ stats is never reported.
1158
+
1159
+ Returns:
1160
+ FileSequence containing the empty files (if any), with their
1161
+ cached stats.
1162
+ """
1163
+ empty = [
1164
+ number for number, info in self._stat.items() if info.st_size == 0
1165
+ ]
1166
+ found = FileSequence(frames=empty, ext=self._ext, pad=self.pad)
1167
+ found.path = self._path
1168
+ found.name = self._name
1169
+ for number in empty:
1170
+ found.cache_stat(number, self._stat[number])
1171
+ return found
1172
+
1173
+ @overload
1174
+ def stat(self) -> dict[int, os.stat_result]: ...
1175
+ @overload
1176
+ def stat(
1177
+ self, frame: SupportsInt | str, force: bool = ..., lazy: bool = ...
1178
+ ) -> os.stat_result | None: ...
1179
+ @overload
1180
+ def stat(
1181
+ self,
1182
+ frame: SupportsInt | str | None = ...,
1183
+ force: bool = ...,
1184
+ lazy: bool = ...,
1185
+ ) -> dict[int, os.stat_result] | os.stat_result | None: ...
1186
+ def stat(
1187
+ self,
1188
+ frame: SupportsInt | str | None = None,
1189
+ force: bool = False,
1190
+ lazy: bool = False,
1191
+ ) -> dict[int, os.stat_result] | os.stat_result | None:
1192
+ """
1193
+ Individual frame file system status.
1194
+
1195
+ Args:
1196
+ frame (int, optional): Frame for which you'd like to return the
1197
+ disk stats.
1198
+ force (bool, optional): Whether to force disk stat query,
1199
+ regardless of caching status.
1200
+ lazy (bool, optional): Whether to query disk stats should no cached
1201
+ value exist.
1202
+
1203
+ Returns:
1204
+ None if a frame has been specified but disk stats have not been
1205
+ cached.
1206
+ stat_result if a frame has been specified and disk stats have
1207
+ been previously cached.
1208
+ dict of disk stats, indexed by int frame if no frame has been
1209
+ specified.
1210
+ """
1211
+ if frame is None:
1212
+ if force or lazy:
1213
+ raise ValueError(
1214
+ "Must specify frame when querying for file disk stats."
1215
+ )
1216
+ return self._stat
1217
+
1218
+ number = int(frame)
1219
+ if force or (lazy and self._stat.get(number) is None):
1220
+ file_name = self._get_sequence_output(number)
1221
+ self.cache_stat(number, os.stat(file_name))
1222
+
1223
+ return self._stat.get(number, None)
1224
+
1225
+ def _aggregate_stats(self) -> None:
1226
+ """
1227
+ Aggregate stats for a variety of file sequence properties.
1228
+
1229
+ This method clears all cached aggregate values before recalculating
1230
+ new values.
1231
+
1232
+ Returns:
1233
+ None
1234
+ """
1235
+ self._ctime = self._mtime = self._size = None
1236
+
1237
+ stats = self._stat
1238
+ if not stats:
1239
+ return
1240
+
1241
+ ctime: float = 0
1242
+ mtime: float = 0
1243
+ size = 0
1244
+ self._sync()
1245
+ for frame in self._frames:
1246
+ stat = stats.get(frame)
1247
+ if stat is None:
1248
+ continue
1249
+ ctime = max(ctime, stat.st_ctime)
1250
+ mtime = max(mtime, stat.st_mtime)
1251
+ size += stat.st_size
1252
+
1253
+ self._ctime, self._mtime, self._size = ctime, mtime, size
1254
+
1255
+ def _name_affixes(self) -> tuple[str, str]:
1256
+ """
1257
+ Calculate the text surrounding the frame in this sequence's names.
1258
+
1259
+ Returns:
1260
+ tuple of (prefix, suffix) such that prefix + padded frame + suffix
1261
+ is a member file name (matches _get_sequence_output for digits).
1262
+ """
1263
+ name = f"{self._name}." if self._name else ""
1264
+ return os.path.join(self._path or "", name), f".{self._ext}"
1265
+
1266
+ def _get_sequence_output(self, frames: str | int | None) -> str:
1267
+ """
1268
+ Calculate a valid file sequence string from the given iterator.
1269
+
1270
+ Args:
1271
+ frames (str): String representation of a frame sequence.
1272
+
1273
+ Returns:
1274
+ str representation of a file sequence.
1275
+ """
1276
+ if frames is None or frames == "":
1277
+ return ""
1278
+
1279
+ if str(frames).isdigit():
1280
+ frames = f"{int(frames):0{self._pad}d}"
1281
+ elif not self._ext:
1282
+ raise ValueError("File sequence extension has not been defined.")
1283
+
1284
+ if self._name:
1285
+ file_name = f"{self._name}.{frames}.{self._ext}"
1286
+ else:
1287
+ file_name = f"{frames}.{self._ext}"
1288
+ return os.path.join(self._path or "", file_name)