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/__init__.py ADDED
@@ -0,0 +1,210 @@
1
+ """
2
+ seqparse: A nifty way to list your file sequences.
3
+
4
+ The seqparse module may be used to ...
5
+
6
+ * Scan specified paths for file sequences and "singletons,"
7
+ * Construct frame and file sequence from supplied values, and
8
+ * Query disk for overall footprint of tracked files.
9
+
10
+ The module also comes supplied with a simple command-line tool named "seqls."
11
+
12
+ Frame sequences are broken down into comma-separated chunks of the format
13
+
14
+ (first frame)-(last frame)x(step)
15
+
16
+ where the following rules apply:
17
+
18
+ * Frame numbers can be zero-padded,
19
+ * Frame step (increment) is always a positive integer,
20
+ * The number of digits in a frame may exceed the padding of a sequence, eg
21
+ "001,010,100,1000",
22
+ * Frame chunks with a specified step will *always* consist of three or more
23
+ frames.
24
+
25
+ Examples of proper frame sequences:
26
+
27
+ * Non-padded sequence, frames == (1, 3, 5, 7): 1-7x2
28
+ * Four-padded sequence, frames == (1, 3, 5, 7): 0001-0007x2
29
+ * Three-padded sequence, frames == (11, 13): 011,013
30
+ * Two-padded sequence (1, 3, 5, 7, 11, 13, 102): 01-07x2,11,13,102
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ from collections.abc import Iterable, Sequence
36
+ import os
37
+ from typing import Any, TYPE_CHECKING
38
+
39
+ if TYPE_CHECKING:
40
+ from seqparse import seqparse, sequences
41
+
42
+ # Anything os.stat_result accepts: another stat_result or a sequence of values.
43
+ StatLike = os.stat_result | Sequence[float]
44
+
45
+ __all__ = (
46
+ "StatLike",
47
+ "get_parser",
48
+ "get_sequence",
49
+ "get_stat_result",
50
+ "get_version",
51
+ "invert",
52
+ "validate_frame_sequence",
53
+ )
54
+
55
+ __version__ = "2.0.0rc1"
56
+
57
+
58
+ ###############################################################################
59
+ # EXPORTED METHODS
60
+
61
+
62
+ def get_parser() -> seqparse.Seqparse:
63
+ """
64
+ Create a new Seqparse instance.
65
+
66
+ Returns:
67
+ Valid Seqparse instance.
68
+
69
+ Examples:
70
+ >>> from seqparse import get_parser
71
+ >>> get_parser()
72
+ Seqparse(sequences=0, singletons=0)
73
+ """
74
+ from seqparse import seqparse
75
+
76
+ return seqparse.Seqparse()
77
+
78
+
79
+ def get_sequence(
80
+ frames: str | Iterable[int | str] | int, pad: int = 1
81
+ ) -> sequences.FrameSequence:
82
+ """
83
+ Create a new FrameSequence instance.
84
+
85
+ Args:
86
+ frames (str, list, tuple, or set): Either a string representation of a
87
+ valid frame sequence or a list-like iterable of integer frames.
88
+ pad (int, optional): Desired zero-padding for the new FrameSequence
89
+ instance. Defaults to *1*.
90
+
91
+ Returns:
92
+ Valid FrameSequence instance.
93
+
94
+ Examples:
95
+ >>> from seqparse import get_sequence
96
+ >>> get_sequence(range(5))
97
+ FrameSequence(pad=1, frames=set([0, 1, 2, 3, 4]))
98
+ >>> get_sequence([1, 2, 3])
99
+ FrameSequence(pad=1, frames=set([1, 2, 3]))
100
+ >>> get_sequence("0001-0005x2")
101
+ FrameSequence(pad=4, frames=set([1, 3, 5]))
102
+ """
103
+ from seqparse import sequences
104
+
105
+ return sequences.FrameSequence(frames, pad=pad)
106
+
107
+
108
+ def get_stat_result(input_stat: StatLike) -> os.stat_result:
109
+ """
110
+ Wrapper for os-specific stat_result instance.
111
+
112
+ Args:
113
+ input_stat (stat_result or stat_result): instance you'd like to clone.
114
+
115
+ Returns:
116
+ nt.stat_result or posix.stat_result, dependent on system platform.
117
+ """
118
+ if type(input_stat) is os.stat_result:
119
+ return input_stat # immutable: no need to copy
120
+ return os.stat_result(input_stat)
121
+
122
+
123
+ def restore_slots(obj: object, state: tuple[Any, Any]) -> None:
124
+ """
125
+ Restore pickled state of the (dict, slots) form for a __slots__ class.
126
+
127
+ Args:
128
+ obj (object): The instance being unpickled.
129
+ state (tuple): (instance __dict__ or None, slot values or None).
130
+ """
131
+ dict_state, slot_state = state
132
+ for name, value in (slot_state or {}).items():
133
+ object.__setattr__(obj, name, value)
134
+ if dict_state:
135
+ obj.__dict__.update(dict_state)
136
+
137
+
138
+ def get_version(pretty: bool = False) -> str:
139
+ """
140
+ Report which version of seqparse you're using.
141
+
142
+ Args:
143
+ pretty (bool) Whether you'd like the super purty, long form version.
144
+
145
+ Returns:
146
+ str seqparse version.
147
+ """
148
+ if pretty:
149
+ return f"seqls (seqparse-v{__version__})"
150
+ return __version__
151
+
152
+
153
+ def invert(
154
+ iterable: sequences.FrameChunk | sequences.FrameSequence,
155
+ ) -> sequences.FrameSequence:
156
+ """
157
+ Create an iterator representing a sequence's missing frames or files.
158
+
159
+ Args:
160
+ iterable (FrameChunk, FrameSequence, or FileSequence): Iterable that
161
+ you'd like to invert.
162
+
163
+ Returns:
164
+ Valid (inverted) FrameSequence from input FrameChunk and FrameSequence
165
+ instances, FileSequence for input FileSequence instances. Note:
166
+ Should the input sequences contain no gaps, will return an empty
167
+ sequence instance.
168
+
169
+ Examples:
170
+ >>> from seqparse import get_sequence, invert
171
+ >>> seq = get_sequence("0001-0005x2")
172
+ >>> print(repr(seq), str(seq))
173
+ FrameSequence(pad=4, frames=set([1, 3, 5])) 0001-0005x2
174
+ >>> inverted = invert(seq)
175
+ >>> print(repr(inverted), str(inverted))
176
+ FrameSequence(pad=4, frames=set([2, 4])) 0002,0004
177
+ """
178
+ from seqparse import sequences
179
+
180
+ if not isinstance(
181
+ iterable, (sequences.FrameChunk, sequences.FrameSequence)
182
+ ):
183
+ raise TypeError(
184
+ "Only able to invert FrameChunk and FrameSequence instances."
185
+ )
186
+
187
+ return iterable.invert()
188
+
189
+
190
+ def validate_frame_sequence(frame_seq: str) -> str | None:
191
+ """
192
+ Whether the supplied string frame (not file) sequence is valid.
193
+
194
+ Args:
195
+ frame_seq (str): The frame sequence you'd like to validate.
196
+
197
+ Returns:
198
+ None for invalid inputs, corrected/validated str frame sequence for
199
+ valid input (see below for examples).
200
+
201
+ Examples:
202
+ >>> from seqparse import validate_frame_sequence
203
+ >>> print(validate_frame_sequence("0001-0001"))
204
+ 0001
205
+ >>> print(validate_frame_sequence("0001-"))
206
+ None
207
+ """
208
+ from seqparse import seqparse
209
+
210
+ return seqparse.Seqparse().validate_frame_sequence(frame_seq)
@@ -0,0 +1 @@
1
+ """Command line interface tools for the seqparse module."""
seqparse/cli/seqls.py ADDED
@@ -0,0 +1,380 @@
1
+ #!/usr/bin/env python
2
+ """
3
+ Command line tool for listing file sequences.
4
+
5
+ Upon installation of the package this script will be accessible via `seqls`
6
+ command on the command line of your choice.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ from collections.abc import Iterable, Iterator, Sequence
13
+ import json
14
+ import os
15
+ import sys
16
+ import time
17
+ from typing import Any
18
+
19
+ import humanize
20
+
21
+ import seqparse
22
+ from seqparse import files, sequences
23
+ from seqparse import seqparse as seqparse_module
24
+
25
+ __all__ = (
26
+ "json_output",
27
+ "long_format_output",
28
+ "main",
29
+ "parse_args",
30
+ "run_main",
31
+ )
32
+
33
+
34
+ def run_main() -> None: # pragma: no cover
35
+ """Main entry point into the script."""
36
+ main(parse_args(sys.argv[1:]))
37
+
38
+
39
+ def main(
40
+ args: argparse.Namespace,
41
+ _debug: bool = False,
42
+ stdin: Iterable[str] | None = None,
43
+ ) -> str | list[str] | None:
44
+ """
45
+ Wrap and initialise the Seqparse class.
46
+
47
+ Args:
48
+ args: Parsed command line arguments (see `parse_args`).
49
+ _debug (bool, optional): Return the result instead of printing it.
50
+ stdin (iterable of str, optional): The lines to read file names from
51
+ when the search paths include "-". Defaults to sys.stdin.
52
+ """
53
+ if args.version:
54
+ # Print the version and exit.
55
+ if _debug:
56
+ return seqparse.get_version(pretty=True)
57
+ print(seqparse.get_version(pretty=True))
58
+ return None
59
+
60
+ parser = _load(args, sys.stdin if stdin is None else stdin)
61
+
62
+ if args.json:
63
+ text = json_output(
64
+ parser.output(seqs_only=args.seqs_only),
65
+ only_missing=args.missing,
66
+ only_empty=args.empty,
67
+ )
68
+ if _debug:
69
+ return text
70
+ print(text)
71
+ return None
72
+
73
+ output = _text_lines(parser, args)
74
+ if _debug:
75
+ return output
76
+
77
+ print("")
78
+ for line in output:
79
+ print(line)
80
+
81
+ return None
82
+
83
+
84
+ def _load(
85
+ args: argparse.Namespace, stdin: Iterable[str]
86
+ ) -> seqparse_module.Seqparse:
87
+ """Scan the search paths and read any names from stdin."""
88
+ if args.max_levels[0] != -1:
89
+ args.max_levels[0] = max(args.max_levels[0], 0)
90
+ if args.min_levels[0] != -1:
91
+ args.min_levels[0] = max(args.min_levels[0], 0)
92
+
93
+ scan_opts = {
94
+ "max_levels": args.max_levels[0],
95
+ "min_levels": args.min_levels[0],
96
+ }
97
+
98
+ parser = seqparse.get_parser()
99
+ parser.scan_options.update(
100
+ {"all": args.all, "stat": args.long_format or args.empty}
101
+ )
102
+
103
+ for search_path in sorted(p for p in args.search_path if p != "-"):
104
+ parser.scan_path(os.path.abspath(search_path), **scan_opts)
105
+
106
+ if "-" in args.search_path:
107
+ for name in _read_names(stdin):
108
+ parser.add_file(name)
109
+
110
+ return parser
111
+
112
+
113
+ def _text_lines(
114
+ parser: seqparse_module.Seqparse, args: argparse.Namespace
115
+ ) -> list[str]:
116
+ """The lines of text output for what the parser found."""
117
+ items = parser.output(missing=args.missing, seqs_only=args.seqs_only)
118
+ if args.empty:
119
+ items = _empty_files(items)
120
+ if args.long_format:
121
+ return long_format_output(items, args.human_readable)
122
+ return [str(x) for x in items]
123
+
124
+
125
+ def _read_names(lines: Iterable[str]) -> Iterator[str]:
126
+ """Yield the file names in the lines, skipping blank ones."""
127
+ for line in lines:
128
+ name = line.rstrip("\r\n")
129
+ if name.strip():
130
+ yield name
131
+
132
+
133
+ def _empty_files(
134
+ items: Iterable[files.File | sequences.FileSequence],
135
+ ) -> Iterator[sequences.FileSequence]:
136
+ """Yield the zero-byte files of each sequence that has any."""
137
+ for item in items:
138
+ if isinstance(item, sequences.FileSequence):
139
+ empty = item.empty_files()
140
+ if empty:
141
+ yield empty
142
+
143
+
144
+ def json_output(
145
+ items: Iterable[files.File | sequences.FileSequence],
146
+ only_missing: bool = False,
147
+ only_empty: bool = False,
148
+ ) -> str:
149
+ """
150
+ Describe the items as a JSON array.
151
+
152
+ Args:
153
+ items: The files and file sequences to describe.
154
+ only_missing (bool, optional): Only describe sequences that have
155
+ missing frames (singletons are left out). Defaults to False.
156
+ only_empty (bool, optional): Only describe sequences that have
157
+ zero-byte files (singletons are left out). Defaults to False.
158
+
159
+ Returns:
160
+ JSON text; see the README for the fields. Sizes, times and empty
161
+ files are null unless the items were scanned with disk stats.
162
+ """
163
+ records: list[dict[str, Any]] = []
164
+
165
+ for item in items:
166
+ if not isinstance(item, sequences.FileSequence):
167
+ if not (only_missing or only_empty):
168
+ records.append(
169
+ {
170
+ "type": "file",
171
+ "path": item.path,
172
+ "name": item.name,
173
+ "size": item.size,
174
+ "mtime": item.mtime,
175
+ "string": str(item),
176
+ }
177
+ )
178
+ continue
179
+
180
+ missing = item.invert().pretty_frames
181
+ if only_missing and not missing:
182
+ continue
183
+
184
+ # Without disk stats there is nothing to tell (as opposed to "none").
185
+ empty = item.empty_files().pretty_frames if item.stat() else None
186
+ if only_empty and not empty:
187
+ continue
188
+
189
+ first = last = 0
190
+ for number, frame in enumerate(item.frames):
191
+ if number == 0:
192
+ first = int(frame)
193
+ last = int(frame)
194
+
195
+ records.append(
196
+ {
197
+ "type": "sequence",
198
+ "path": item.path,
199
+ "name": item.name,
200
+ "ext": item.ext,
201
+ "pad": item.pad,
202
+ "frames": item.pretty_frames,
203
+ "count": len(item),
204
+ "first": first,
205
+ "last": last,
206
+ "missing": missing,
207
+ "empty": empty,
208
+ "size": item.size,
209
+ "mtime": item.mtime,
210
+ "string": str(item),
211
+ }
212
+ )
213
+
214
+ return json.dumps(records, indent=2)
215
+
216
+
217
+ def long_format_output(
218
+ items: Iterable[files.File | sequences.FileSequence],
219
+ human_readable: bool = False,
220
+ ) -> list[str]:
221
+ """Generate long format output for the provided items."""
222
+ bits = []
223
+ output = []
224
+
225
+ for item in items:
226
+ size: int | str | None = item.size
227
+ if size is None:
228
+ size = "----"
229
+ elif human_readable:
230
+ size = humanize.naturalsize(size, gnu=True)
231
+
232
+ mtime = "----"
233
+ if item.mtime is not None:
234
+ mtime = time.strftime("%Y/%m/%d %H:%M", time.localtime(item.mtime))
235
+ bits.append((size, mtime, str(item)))
236
+
237
+ # Find the maximum width of the sequence sizes; we'll use this to pad
238
+ # the output.
239
+ if bits:
240
+ max_len = max(len(str(x[0])) for x in bits)
241
+ for bit in bits:
242
+ output.append(f"{bit[0]:<{max_len:d}} {bit[1]} {bit[2]}")
243
+
244
+ return output
245
+
246
+
247
+ def parse_args(args: Sequence[str]) -> argparse.Namespace:
248
+ """Parse any input arguments."""
249
+ parser = argparse.ArgumentParser(description=__doc__)
250
+
251
+ parser.add_argument(
252
+ "search_path",
253
+ default=["."],
254
+ help=(
255
+ "Paths that you'd like to search for file sequences. Use '-' to "
256
+ "read file names (one per line) from standard input instead; "
257
+ "they are used as written, so -a, --maxdepth and --mindepth do "
258
+ "not apply to them."
259
+ ),
260
+ nargs="*",
261
+ )
262
+ parser.add_argument(
263
+ "-a",
264
+ "--all",
265
+ action="store_true",
266
+ help="Do not ignore entries starting with '.'.",
267
+ )
268
+
269
+ parser.add_argument(
270
+ "-H",
271
+ "--human-readable",
272
+ action="store_true",
273
+ dest="human_readable",
274
+ help=(
275
+ "with -l/--long, print sizes in human readable format (e.g., 1K "
276
+ "234M 2G)."
277
+ ),
278
+ )
279
+
280
+ parser.add_argument(
281
+ "-l",
282
+ "--long",
283
+ action="store_true",
284
+ dest="long_format",
285
+ help="Use a long listing format.",
286
+ )
287
+
288
+ parser.add_argument(
289
+ "--maxdepth",
290
+ default=[-1],
291
+ dest="max_levels",
292
+ help=(
293
+ "Descend at most MAX_LEVELS (a non-negative integer) levels of "
294
+ "directories below the starting points; 0 scans only the "
295
+ "starting points themselves."
296
+ ),
297
+ nargs=1,
298
+ required=False,
299
+ type=int,
300
+ )
301
+
302
+ parser.add_argument(
303
+ "--mindepth",
304
+ default=[-1],
305
+ dest="min_levels",
306
+ help=(
307
+ "Do not scan at levels less than MIN_LEVELS (a non-negative "
308
+ "integer); 1 scans every level except the starting points."
309
+ ),
310
+ nargs=1,
311
+ required=False,
312
+ type=int,
313
+ )
314
+
315
+ problems = parser.add_mutually_exclusive_group()
316
+ problems.add_argument(
317
+ "-m",
318
+ "--missing",
319
+ action="store_true",
320
+ help=(
321
+ "Whether to invert output file sequences to only report the "
322
+ "missing frames."
323
+ ),
324
+ )
325
+ problems.add_argument(
326
+ "--empty",
327
+ action="store_true",
328
+ help=(
329
+ "Only report the zero-byte frames of each sequence (the likely "
330
+ "debris of a crashed render), as a frame sequence."
331
+ ),
332
+ )
333
+
334
+ parser.add_argument(
335
+ "-S",
336
+ "--seqs-only",
337
+ action="store_true",
338
+ dest="seqs_only",
339
+ help="Whether to filter out all non-sequence files.",
340
+ )
341
+
342
+ parser.add_argument(
343
+ "--json",
344
+ action="store_true",
345
+ help=(
346
+ "Print JSON instead of text: sizes (bytes) and modification "
347
+ "times (epoch seconds) are included with -l/--long, and with "
348
+ "-m/--missing only sequences that have gaps are listed."
349
+ ),
350
+ )
351
+
352
+ parser.add_argument(
353
+ "-v",
354
+ "--version",
355
+ action="store_true",
356
+ help="Print the version and exit.",
357
+ )
358
+
359
+ # Parse the arguments.
360
+ parsed_args = parser.parse_args(args)
361
+
362
+ # Names from stdin need not exist, so there is nothing to stat.
363
+ if "-" in parsed_args.search_path and (
364
+ parsed_args.long_format or parsed_args.empty
365
+ ):
366
+ parser.error(
367
+ "-l/--long and --empty need files on disk, not names from stdin"
368
+ )
369
+
370
+ # We'll assume that if the user is requesting missing (or empty) sequence
371
+ # files that he/she doesn't want to see any singletons.
372
+ if parsed_args.missing or parsed_args.empty:
373
+ parsed_args.seqs_only = True
374
+
375
+ return parsed_args
376
+
377
+
378
+ if __name__ == "__main__":
379
+ run_main()
380
+ sys.exit(0)