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/seqparse.py ADDED
@@ -0,0 +1,532 @@
1
+ """The main engine for the seqparse module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import collections
6
+ from collections.abc import Iterable, Iterator
7
+ import operator
8
+ import os
9
+ from typing import Any, Literal, overload, TypedDict, TypeGuard
10
+
11
+ from seqparse import containers, files, regex
12
+
13
+ # Aliased: Seqparse.sequences (a property) would shadow the module name in
14
+ # the class's method annotations.
15
+ from seqparse import sequences as sequences_module
16
+
17
+ __all__ = ("Location", "ScanOptions", "Seqparse")
18
+
19
+ PathLike = str | os.DirEntry[str]
20
+
21
+
22
+ class Location(TypedDict):
23
+ """Everything tracked in one directory."""
24
+
25
+ seqs: collections.defaultdict[str, containers.FileSequenceContainer]
26
+ files: containers.SingletonContainer
27
+
28
+
29
+ class ScanOptions(TypedDict):
30
+ """Options used while scanning disk for files."""
31
+
32
+ all: bool
33
+ stat: bool
34
+
35
+
36
+ def _new_location() -> Location:
37
+ """An empty Location (the default for Seqparse.locations)."""
38
+ return {
39
+ "seqs": collections.defaultdict(containers.FileSequenceContainer),
40
+ "files": containers.SingletonContainer(),
41
+ }
42
+
43
+
44
+ def _is_dir_entry(item: object) -> TypeGuard[os.DirEntry[str]]:
45
+ """Whether item is a DirEntry (by name, so look-alikes work too)."""
46
+ return type(item).__name__ == "DirEntry"
47
+
48
+
49
+ def _split_posix(path: str) -> tuple[str, str]:
50
+ """os.path.split for POSIX paths, without its per-call overhead."""
51
+ cut = path.rfind("/") + 1
52
+ head, tail = path[:cut], path[cut:]
53
+ if head and head != "/" * len(head):
54
+ head = head.rstrip("/")
55
+ return head, tail
56
+
57
+
58
+ def _split_native(path: str) -> tuple[str, str]:
59
+ """
60
+ os.path.split, with alternate separators made primary first.
61
+
62
+ On Windows "C:/a/b" and "C:\\a\\b" then name the same directory (and
63
+ so share one entry in Seqparse.locations).
64
+ """
65
+ if os.altsep:
66
+ path = path.replace(os.altsep, os.sep)
67
+ return os.path.split(path)
68
+
69
+
70
+ _split = _split_posix if os.sep == "/" and not os.altsep else _split_native
71
+
72
+
73
+ def _strip_trailing_sep(path: str) -> str:
74
+ """
75
+ Remove trailing separators, keeping roots ("/", "C:\\", UNC shares).
76
+
77
+ Args:
78
+ path (str): The path to clean up.
79
+
80
+ Returns:
81
+ str path without trailing separators, unless it is a root.
82
+ """
83
+ drive, rest = os.path.splitdrive(path)
84
+ stripped = rest.rstrip(os.sep + (os.altsep or ""))
85
+ return drive + (stripped or rest)
86
+
87
+
88
+ def _dir_key(path: str) -> tuple[int, int] | str:
89
+ """
90
+ Identity of a directory, for spotting symlink loops.
91
+
92
+ (device, inode) costs one stat call, where os.path.realpath costs one per
93
+ path component. Paths that can't be stat'd (os.scandir will report
94
+ those) and filesystems without inode numbers fall back to realpath.
95
+ """
96
+ try:
97
+ info = os.stat(path)
98
+ except OSError:
99
+ return os.path.realpath(path)
100
+ if info.st_ino:
101
+ return (info.st_dev, info.st_ino)
102
+ return os.path.realpath(path) # pragma: no cover
103
+
104
+
105
+ def _is_ancestor(path: str, parents: Iterable[str]) -> bool:
106
+ """Whether path resolves to the same directory as one of parents."""
107
+ real = os.path.realpath(path)
108
+ return any(os.path.realpath(parent) == real for parent in parents)
109
+
110
+
111
+ def _stat(
112
+ file_name: str, entry: os.DirEntry[str] | None = None
113
+ ) -> os.stat_result:
114
+ """
115
+ Disk stats for a file, following symlinks.
116
+
117
+ Args:
118
+ file_name (str): Path to the file.
119
+ entry (DirEntry, optional): The file's DirEntry when it was found via
120
+ scan_path; its cached stat is used in preference to os.stat.
121
+
122
+ Returns:
123
+ stat_result for the file.
124
+ """
125
+ if entry:
126
+ return entry.stat(follow_symlinks=True)
127
+ return os.stat(file_name)
128
+
129
+
130
+ ###############################################################################
131
+ # Class: Seqparse
132
+
133
+
134
+ class Seqparse(regex.SeqparseRegexMixin):
135
+ """
136
+ Storage and parsing engine for file sequences.
137
+
138
+ The primary usage for this class is to scan specified locations on disk for
139
+ file sequences and singletons (any file that cannot be classified as a
140
+ member of a file sequence).
141
+
142
+ Examples:
143
+
144
+ With the following file structure ...
145
+
146
+ test_dir/
147
+ TEST_DIR.0001.tif
148
+ TEST_DIR.0002.tif
149
+ TEST_DIR.0003.tif
150
+ TEST_DIR.0004.tif
151
+ TEST_DIR.0010.tif
152
+ SINGLETON.jpg
153
+
154
+ >>> from seqparse.seqparse import Seqparse
155
+ >>> parser = Seqparse()
156
+ >>> parser.scan_path("test_dir")
157
+ >>> for item in parser.output():
158
+ ... print str(item)
159
+ ...
160
+ test_dir/TEST_DIR.0001-0004,0010.tif
161
+ test_dir/SINGLETON.jpg
162
+ >>> for item in parser.output(seqs_only=True):
163
+ ... print str(item)
164
+ ...
165
+ test_dir/TEST_DIR.0001-0004,0010.tif
166
+ >>> for item in parser.output(missing=True):
167
+ ... print str(item)
168
+ ...
169
+ test_dir/TEST_DIR.0005-0009.tif
170
+ """
171
+
172
+ def __init__(self) -> None:
173
+ """Initialise the instance."""
174
+ super().__init__()
175
+
176
+ self._locs: collections.defaultdict[str, Location] = (
177
+ collections.defaultdict(_new_location)
178
+ )
179
+ self._options: ScanOptions = {"all": False, "stat": False}
180
+
181
+ def __repr__(self) -> str: # pragma: no cover
182
+ """Pretty representation of the instance."""
183
+ num_seqs = sum(1 for _ in self.output(seqs_only=True))
184
+ num_files = sum(1 for _ in self.output()) - num_seqs
185
+ return (
186
+ f"{type(self).__name__}(sequences={num_seqs}, "
187
+ f"singletons={num_files})"
188
+ )
189
+
190
+ @property
191
+ def locations(self) -> collections.defaultdict[str, Location]:
192
+ """A dictionary of tracked singletons and file sequences."""
193
+ return self._locs
194
+
195
+ @property
196
+ def scan_options(self) -> ScanOptions:
197
+ """A dictionary of options used while scanning disk for files."""
198
+ return self._options
199
+
200
+ @property
201
+ def sequences(
202
+ self,
203
+ ) -> dict[
204
+ str, collections.defaultdict[str, containers.FileSequenceContainer]
205
+ ]:
206
+ """A dictionary of tracked file sequences."""
207
+ return self._get_data("seqs")
208
+
209
+ @property
210
+ def singletons(self) -> dict[str, containers.SingletonContainer]:
211
+ """A dictionary of tracked singleton files."""
212
+ return self._get_data("files")
213
+
214
+ def add_file(self, file_name: PathLike) -> None:
215
+ """
216
+ Add a file to the parser instance.
217
+
218
+ Args:
219
+ file_name (str): The name of the file you'd like to add to the
220
+ parser.
221
+
222
+ Returns:
223
+ None
224
+ """
225
+ if _is_dir_entry(file_name):
226
+ self._add_path(file_name.path, True, file_name)
227
+ else:
228
+ self._add_path(str(file_name), False, None)
229
+
230
+ def _add_path(
231
+ self, path: str, on_disk: bool, entry: os.DirEntry[str] | None
232
+ ) -> None:
233
+ """
234
+ Add a file (or, unless on_disk, a whole file sequence) by name.
235
+
236
+ Args:
237
+ path (str): The file (or file sequence) name.
238
+ on_disk (bool): Whether path is a single file that exists on disk.
239
+ entry (DirEntry or None): The file's DirEntry, if it has one.
240
+
241
+ Returns:
242
+ None
243
+ """
244
+ dir_name, base_name = _split(path)
245
+
246
+ # A file found on disk is a single frame; a frame *sequence* in its
247
+ # name (eg "foo.1-3.exr") is just part of a singleton's name. Strings
248
+ # passed in directly may describe a whole sequence of files.
249
+ match = (self._file_expr if on_disk else self._fseq_expr).match(
250
+ base_name
251
+ )
252
+
253
+ if match:
254
+ seq_name, frames, ext_name = match.groups()
255
+ seq_name = seq_name or ""
256
+
257
+ loc = self.locations[dir_name]
258
+ sequence = loc["seqs"][seq_name]
259
+
260
+ # Set the name and path properties at initialization.
261
+ if not sequence:
262
+ sequence.name = seq_name
263
+ sequence.path = dir_name
264
+
265
+ # We'll assume that a frame sequence is properly formed -- and use
266
+ # the length of the first frame as the padding. The FrameSequence
267
+ # to which we're adding the frames will do the actual validation.
268
+ if frames.isdecimal():
269
+ pad = len(frames)
270
+ else:
271
+ first_chunk = frames.lstrip(",").split(",")[0]
272
+ pad = len(first_chunk.partition("-")[0])
273
+
274
+ ext = sequence[ext_name]
275
+ ext[pad].add(frames)
276
+
277
+ # Disk stats only make sense for a single file (frame).
278
+ if self.scan_options["stat"] and frames.isdigit():
279
+ ext[pad].cache_stat(int(frames), _stat(path, entry))
280
+
281
+ else:
282
+ loc = self.locations[dir_name]
283
+
284
+ singletons = loc["files"]
285
+
286
+ # Set the path properties at initialization.
287
+ if not singletons:
288
+ singletons.path = dir_name
289
+
290
+ singletons.add(base_name)
291
+ if self.scan_options["stat"]:
292
+ singletons.cache_stat(base_name, _stat(path, entry))
293
+
294
+ @overload
295
+ def output(
296
+ self, missing: Literal[True], seqs_only: bool = ...
297
+ ) -> Iterator[sequences_module.FileSequence]: ...
298
+ @overload
299
+ def output(
300
+ self, missing: bool = ..., *, seqs_only: Literal[True]
301
+ ) -> Iterator[sequences_module.FileSequence]: ...
302
+ @overload
303
+ def output(
304
+ self, missing: bool = False, seqs_only: bool = False
305
+ ) -> Iterator[files.File | sequences_module.FileSequence]: ...
306
+ def output(
307
+ self, missing: bool = False, seqs_only: bool = False
308
+ ) -> Iterator[files.File | sequences_module.FileSequence]:
309
+ """
310
+ Yield a list of contained singletons and file sequences.
311
+
312
+ Args:
313
+ missing (bool, optional): Whether to yield "inverted" file
314
+ sequences (ie, the missing files). Defaults to False. NOTE:
315
+ Using this option implies that seqs_only == True.
316
+ seqs_only (bool, optional): Whether to only yield file sequences
317
+ (if any). Defaults to False.
318
+
319
+ Yields:
320
+ File and/or FileSequence instances, depending on input arguments.
321
+ """
322
+ if missing:
323
+ seqs_only = True
324
+
325
+ for root_dir in sorted(self.locations):
326
+ data = self.locations[root_dir]
327
+ for container in sorted(
328
+ data["seqs"].values(), key=operator.attrgetter("full_name")
329
+ ):
330
+ for file_seq in container.output():
331
+ if not missing:
332
+ yield file_seq
333
+ continue
334
+ inverted = file_seq.invert()
335
+ # No gaps: nothing is missing.
336
+ if inverted:
337
+ yield inverted
338
+
339
+ if seqs_only:
340
+ continue
341
+
342
+ # output() already yields the files sorted by name.
343
+ yield from data["files"].output()
344
+
345
+ def scan_path(
346
+ self,
347
+ search_paths: str | list[str] | set[str] | tuple[str, ...],
348
+ max_levels: int = -1,
349
+ min_levels: int = -1,
350
+ ) -> None:
351
+ """
352
+ Scan supplied path, add all discovered files to the instance.
353
+
354
+ Args:
355
+ search_paths (str): The location(s) on disk you'd like to scan for
356
+ file sequences and singletons.
357
+ max_levels (int, optional): Descend at most the specified number (a
358
+ non- negative integer) of directories below the starting point.
359
+ max_levels == 0 means only scan the starting-point itself.
360
+ min_levels (int, optional): Do not scan at levels less than
361
+ specified number (a non-negative integer). min_levels == 1
362
+ means scan all levels except the starting-point.
363
+
364
+ Returns:
365
+ None
366
+ """
367
+ if isinstance(search_paths, (list, set, tuple)):
368
+ for search_path in search_paths:
369
+ self.scan_path(
370
+ search_path, max_levels=max_levels, min_levels=min_levels
371
+ )
372
+ return
373
+ if os.path.isfile(search_paths):
374
+ # Treat it exactly as a directory scan would treat the same file.
375
+ self._add_path(search_paths, True, None)
376
+ return
377
+
378
+ search_path = _strip_trailing_sep(search_paths)
379
+
380
+ for cur_level, dir_entries, file_entries in self._scandir_walk(
381
+ search_path
382
+ ):
383
+ max_out = max_levels > -1 and cur_level >= max_levels
384
+ min_out = min_levels > -1 and cur_level < min_levels
385
+
386
+ if max_out:
387
+ del dir_entries[:]
388
+ if min_out:
389
+ del file_entries[:]
390
+
391
+ self._add_from_scan(file_entries)
392
+
393
+ def _add_from_scan(self, file_entries: Iterable[os.DirEntry[str]]) -> None:
394
+ """
395
+ Shortcut for adding file sequences from os/scandir.walk.
396
+
397
+ Args:
398
+ file_entries (iterable): Iterable (list-like object or generator)
399
+ of scandir-style DirEntry instances for files discovered on
400
+ disk.
401
+
402
+ Returns:
403
+ None
404
+ """
405
+ for file_entry in file_entries:
406
+ self.add_file(file_entry)
407
+
408
+ @overload
409
+ def _get_data(
410
+ self, typ: Literal["seqs"]
411
+ ) -> dict[
412
+ str, collections.defaultdict[str, containers.FileSequenceContainer]
413
+ ]: ...
414
+ @overload
415
+ def _get_data(
416
+ self, typ: Literal["files"]
417
+ ) -> dict[str, containers.SingletonContainer]: ...
418
+ def _get_data(
419
+ self, typ: Literal["seqs", "files"]
420
+ ) -> (
421
+ dict[
422
+ str, collections.defaultdict[str, containers.FileSequenceContainer]
423
+ ]
424
+ | dict[str, containers.SingletonContainer]
425
+ ):
426
+ """
427
+ Return dictionary of the specified data type from the instance.
428
+
429
+ Args:
430
+ typ (str): "seqs" (for file sequences) or "files" (for singletons).
431
+
432
+ Returns:
433
+ dict of all data of the specified type, indexed by containing
434
+ directory.
435
+ """
436
+ output: dict[str, Any] = {}
437
+ for loc, data in self.locations.items():
438
+ if data[typ]:
439
+ output[loc] = data[typ]
440
+ return output
441
+
442
+ def _scandir_walk(
443
+ self,
444
+ search_path: str,
445
+ follow_symlinks: bool = True,
446
+ _level: int = 0,
447
+ _ancestors: frozenset[tuple[int, int] | str] = frozenset(),
448
+ _parents: tuple[str, ...] = (),
449
+ ) -> Iterator[tuple[int, list[os.DirEntry[str]], list[os.DirEntry[str]]]]:
450
+ """
451
+ Recursively yield DirEntry objects for given directory.
452
+
453
+ A directory that resolves to one of its own ancestors (a symlink loop)
454
+ is skipped, as are subdirectories that cannot be read. Other symlinked
455
+ directories are followed, so their files are reported under every path
456
+ that reaches them (like `find -L`).
457
+
458
+ Args:
459
+ search_path (str): Directory to scan for files.
460
+ follow_symlinks (bool, optional): Whether to follow symlinks
461
+ dicovered at scan time. Defaults to True.
462
+
463
+ Yields:
464
+ tuple of (depth below the starting point, list of directory
465
+ DirEntry instances, list of file DirEntry instances). Removing
466
+ items from the directory list prevents descending into them.
467
+ """
468
+ key = _dir_key(search_path)
469
+ # Some network/FUSE filesystems reuse inode numbers: confirm a match
470
+ # by path before treating it as a symlink loop.
471
+ if key in _ancestors and _is_ancestor(search_path, _parents):
472
+ return
473
+ _ancestors = _ancestors | {key}
474
+
475
+ dir_entries: list[os.DirEntry[str]] = []
476
+ file_entries: list[os.DirEntry[str]] = []
477
+ try:
478
+ entries = list(os.scandir(search_path))
479
+ except OSError:
480
+ # Let errors on the starting point propagate to the caller.
481
+ if not _level:
482
+ raise
483
+ return
484
+
485
+ for entry in entries:
486
+ if entry.name.startswith(".") and not self.scan_options["all"]:
487
+ continue
488
+ if entry.is_dir(follow_symlinks=follow_symlinks):
489
+ dir_entries.append(entry)
490
+ elif entry.is_file(follow_symlinks=follow_symlinks):
491
+ file_entries.append(entry)
492
+
493
+ yield _level, dir_entries, file_entries
494
+
495
+ for entry in dir_entries:
496
+ yield from self._scandir_walk(
497
+ entry.path,
498
+ follow_symlinks=follow_symlinks,
499
+ _level=_level + 1,
500
+ _ancestors=_ancestors,
501
+ _parents=(*_parents, search_path),
502
+ )
503
+
504
+ @staticmethod
505
+ def validate_frame_sequence(frame_seq: str) -> str | None:
506
+ """
507
+ Whether the supplied frame (not file) sequence is valid.
508
+
509
+ Args:
510
+ frame_seq (str): The string representation of the frame sequence
511
+ to validate.
512
+
513
+ Returns:
514
+ None if the supplied sequence is invalid, a (possibly corrected)
515
+ string file sequence if valid.
516
+
517
+ Examples:
518
+ >>> from seqparse.seqparse import Seqparse
519
+ >>> parser = Seqparse()
520
+ >>> print parser.validate_frame_sequence("0001-0001")
521
+ 0001
522
+ >>> print parser.validate_frame_sequence("0001-")
523
+ None
524
+ >>> print parser.validate_frame_sequence("3,1,5,7")
525
+ 1-7x2
526
+ """
527
+ try:
528
+ seq = sequences_module.FrameSequence(frame_seq)
529
+ except ValueError:
530
+ return None
531
+
532
+ return str(seq)