Debian Codegraph @

pyvista/_cli/convert.py

raw
1 """`pyvista convert file.in file.out` CLI."""
2
3 from __future__ import annotations
4
5 from pathlib import Path
6 from typing import Annotated
7 import warnings
8
9 from cyclopts import Parameter
10 from rich.progress import BarColumn
11 from rich.progress import MofNCompleteColumn
12 from rich.progress import Progress
13 from rich.progress import TextColumn
14 from rich.progress import TimeElapsedColumn
15 from rich.progress import TimeRemainingColumn
16
17 import pyvista as pv
18
19 from .app import app
20 from .utils import HELP_FORMATTER
21 from .utils import _check_paths_exist
22 from .utils import _console_error
23 from .utils import _filter_multiblock_children
24
25
26 def _is_extension_only(file_out: str) -> bool:
27 """Return ``True`` when ``file_out`` specifies only an extension (``.pv`` or ``dir/.pv``)."""
28 path = Path(file_out)
29 return not path.suffix and path.stem.startswith('.')
30
31
32 def _validate_out_has_extension(file_out: str) -> None:
33 """Raise ``ValueError`` when ``file_out`` is missing a file extension."""
34 if not Path(file_out).suffix and not _is_extension_only(file_out):
35 msg = 'Output file must have a file extension.'
36 raise ValueError(msg)
37
38
39 @app.command(
40 usage=f'Usage: [bold]{pv.__name__} convert FILE-IN [FILE-IN...] FILE-OUT',
41 help_formatter=HELP_FORMATTER,
42 )
43 def _convert(
44 files: Annotated[
45 list[str],
46 Parameter(
47 name='files',
48 consume_multiple=True,
49 negative='',
50 help=(
51 'One or more input files followed by the output spec. '
52 'Inputs may include glob patterns (e.g. ``*.vtu``) and must be readable '
53 'with ``pyvista.read``. The final token is the output: a full filename '
54 '(``bar.xyz``) when converting a single input, or an extension-only spec '
55 '(``.xyz`` or ``dir/.xyz``) which reuses each input stem. A bare ``.xyz`` '
56 'writes adjacent to each input; ``dir/.xyz`` writes into ``dir/``.'
57 ),
58 ),
59 ],
60 ) -> None:
61 """Convert a mesh file to another format.
62
63 One or more inputs may be supplied, and glob patterns are expanded. When multiple
64 inputs are given, the output must be an extension-only spec (``.xyz`` or
65 ``dir/.xyz``) so each input's stem is reused. A bare ``.xyz`` writes the output
66 adjacent to each input; ``dir/.xyz`` writes into the given ``dir``.
67
68 MultiBlock files (``.vtm``/``.vtmb``) are paired on disk with a sibling sidecar
69 directory (e.g. ``parent.vtm`` -> ``parent/parent_0.vtp``). Pass the parent
70 ``.vtm`` directly to convert a MultiBlock as a single output; a recursive glob
71 like ``**/*`` may also pick up the sidecar children. When both a parent and its
72 sidecar children appear in the input list the children are dropped automatically
73 to preserve the 1:1 input/output mapping.
74
75 Sample usage:
76 ```bash
77 pyvista convert foo.abc bar.xyz
78 Saved: bar.xyz
79
80 pyvista convert foo.abc .xyz
81 Saved: foo.xyz
82
83 pyvista convert sub/*.vtu .pv
84 # Writes sub/a.pv, sub/b.pv, ... next to each input
85
86 pyvista convert sub/*.vtu out/.pv
87 # Writes out/a.pv, out/b.pv, ... into the explicit out directory
88 ```
89 """
90 if len(files) < 2:
91 _console_error(
92 app=app,
93 message='convert requires at least one input file and an output spec.',
94 )
95
96 file_out = files[-1]
97 file_in_tokens = files[:-1]
98
99 try:
100 _validate_out_has_extension(file_out)
101 except ValueError as e:
102 _console_error(app=app, message=str(e))
103
104 try:
105 input_paths = _check_paths_exist(file_in_tokens)
106 except ValueError as e:
107 _console_error(app=app, message=str(e))
108
109 input_paths, dropped = _filter_multiblock_children(input_paths)
110 if dropped:
111 n = len(dropped)
112 listed = ', '.join(str(p) for p in dropped[:5])
113 if n > 5:
114 listed += f', ... ({n - 5} more)'
115 app.console.print(
116 f'[yellow]Skipping {n} file(s) inside MultiBlock sidecar directories:[/yellow] '
117 f'{listed}'
118 )
119
120 path_out = Path(file_out)
121 ext_only = _is_extension_only(file_out)
122 if not ext_only and len(input_paths) > 1:
123 _console_error(
124 app=app,
125 message=(
126 f'Cannot write {len(input_paths)} inputs to a single named output '
127 f'{file_out!r}. Use an extension-only output spec (e.g. '
128 f"'{path_out.suffix}') to reuse each input's stem."
129 ),
130 )
131
132 if len(input_paths) > 1:
133 _convert_many(input_paths, path_out)
134 else:
135 _convert_one(input_paths[0], path_out, ext_only=ext_only, announce=True)
136
137
138 def _read_mesh(path_in: Path) -> pv.DataObject:
139 """Read ``path_in`` while suppressing :class:`pv.InvalidMeshWarning`."""
140 with warnings.catch_warnings():
141 warnings.filterwarnings('ignore', category=pv.InvalidMeshWarning)
142 return pv.read(path_in)
143
144
145 def _resolve_out_path(path_in: Path, path_out: Path, *, ext_only: bool) -> Path:
146 """Compute the per-input output path.
147
148 A bare extension-only spec (``.pv``) is written next to each input. An extension-only
149 spec with an explicit parent (``out/.pv``) is written into that parent.
150 """
151 if not ext_only:
152 return path_out
153 out_dir = path_in.parent if str(path_out.parent) == '.' else path_out.parent
154 return out_dir / f'{path_in.stem}{path_out.stem}'
155
156
157 def _convert_one(
158 path_in: Path,
159 path_out: Path,
160 *,
161 ext_only: bool,
162 announce: bool,
163 ) -> None:
164 """Read a single input, save it under the resolved output path, and optionally announce."""
165 out_path = _resolve_out_path(path_in, path_out, ext_only=ext_only)
166 out_path.parent.mkdir(parents=True, exist_ok=True)
167
168 try:
169 mesh = _read_mesh(path_in)
170 except Exception as e: # noqa: BLE001
171 _console_error(app=app, message=f'Failed to read input file: {path_in}\n{e}')
172
173 try:
174 mesh.save(out_path)
175 except Exception as e: # noqa: BLE001
176 _console_error(app=app, message=f'Failed to save output file: {out_path}\n{e}')
177
178 if announce:
179 app.console.print(f'[green]Saved:[/green] {out_path}')
180
181
182 def _convert_many(input_paths: list[Path], path_out: Path) -> None:
183 """Convert each input under a progress bar and report the destination directory(s)."""
184 columns = (
185 TextColumn('[progress.description]{task.description}'),
186 BarColumn(),
187 MofNCompleteColumn(),
188 TextColumn('•'),
189 TimeElapsedColumn(),
190 TextColumn('<'),
191 TimeRemainingColumn(),
192 )
193 out_dirs: set[Path] = set()
194 with Progress(*columns, console=app.console, transient=False) as progress:
195 task = progress.add_task('Converting', total=len(input_paths))
196 for path_in in input_paths:
197 progress.update(task, description=f'Converting [cyan]{path_in.name}[/cyan]')
198 out_path = _resolve_out_path(path_in, path_out, ext_only=True)
199 out_dirs.add(out_path.parent)
200 _convert_one(path_in, path_out, ext_only=True, announce=False)
201 progress.update(task, advance=1)
202
203 if len(out_dirs) == 1:
204 app.console.print(
205 f'[green]Saved {len(input_paths)} files to:[/green] {next(iter(out_dirs))}/'
206 )
207 else:
208 app.console.print(
209 f'[green]Saved {len(input_paths)} files across {len(out_dirs)} directories.[/green]'
210 )