Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make load functions compatible with pathlib #1176

Merged
merged 2 commits into from
Aug 16, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 45 additions & 20 deletions vedo/file_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@
"""

########################################################################
def load(inputobj: Union[list, str], unpack=True, force=False) -> Any:
def load(inputobj: Union[list, str, os.PathLike], unpack=True, force=False) -> Any:
"""
Load any vedo objects from file or from the web.

Expand All @@ -199,6 +199,11 @@ def load(inputobj: Union[list, str], unpack=True, force=False) -> Any:
show(g)
```
"""
if isinstance(inputobj, list):
inputobj = [str(f) for f in inputobj]
else:
inputobj = str(inputobj)

acts = []
if utils.is_sequence(inputobj):
flist = inputobj
Expand Down Expand Up @@ -607,13 +612,14 @@ def file_info(file_path: str) -> Tuple[str, str]:


###################################################################
def loadStructuredPoints(filename, as_points=True):
def loadStructuredPoints(filename: Union[str, os.PathLike], as_points=True):
"""
Load and return a `vtkStructuredPoints` object from file.

If `as_points` is True, return a `Points` object
instead of a `vtkStructuredPoints`.
"""
filename = str(filename)
reader = vtki.new("StructuredPointsReader")
reader.SetFileName(filename)
reader.Update()
Expand All @@ -626,8 +632,9 @@ def loadStructuredPoints(filename, as_points=True):
return reader.GetOutput()

########################################################################
def loadStructuredGrid(filename):
def loadStructuredGrid(filename: Union[str, os.PathLike]):
"""Load and return a `vtkStructuredGrid` object from file."""
filename = str(filename)
if filename.endswith(".vts"):
reader = vtki.new("XMLStructuredGridReader")
else:
Expand All @@ -638,8 +645,9 @@ def loadStructuredGrid(filename):


###################################################################
def load3DS(filename: str) -> Assembly:
def load3DS(filename: Union[str, os.PathLike]) -> Assembly:
"""Load `3DS` file format from file."""
filename = str(filename)
renderer = vtki.vtkRenderer()
renWin = vtki.vtkRenderWindow()
renWin.AddRenderer(renderer)
Expand Down Expand Up @@ -669,8 +677,9 @@ def load3DS(filename: str) -> Assembly:
return vedo.Assembly(wrapped_acts)

########################################################################
def loadOFF(filename: str) -> Mesh:
def loadOFF(filename: Union[str, os.PathLike]) -> Mesh:
"""Read the OFF file format (polygonal mesh)."""
filename = str(filename)
with open(filename, "r", encoding="UTF-8") as f:
lines = f.readlines()

Expand Down Expand Up @@ -708,20 +717,22 @@ def loadOFF(filename: str) -> Mesh:
return Mesh(utils.buildPolyData(vertices, faces))

########################################################################
def loadGeoJSON(filename: str) -> Mesh:
def loadGeoJSON(filename: Union[str, os.PathLike]) -> Mesh:
"""Load GeoJSON files."""
filename = str(filename)
jr = vtki.new("GeoJSONReader")
jr.SetFileName(filename)
jr.Update()
return Mesh(jr.GetOutput())

########################################################################
def loadDolfin(filename: str) -> Union[Mesh, "vedo.TetMesh", None]:
def loadDolfin(filename: Union[str, os.PathLike]) -> Union[Mesh, "vedo.TetMesh", None]:
"""
Reads a `Fenics/Dolfin` file format (.xml or .xdmf).

Return a `Mesh` or a `TetMesh` object.
"""
filename = str(filename)
try:
import dolfin
except ImportError:
Expand Down Expand Up @@ -751,8 +762,9 @@ def loadDolfin(filename: str) -> Union[Mesh, "vedo.TetMesh", None]:


########################################################################
def loadPVD(filename: str) -> Union[List[Any], None]:
def loadPVD(filename: Union[str, os.PathLike]) -> Union[List[Any], None]:
"""Read paraview files."""
filename = str(filename)
import xml.etree.ElementTree as et

tree = et.parse(filename)
Expand All @@ -779,12 +791,13 @@ def loadPVD(filename: str) -> Union[List[Any], None]:
return listofobjs

########################################################################
def loadNeutral(filename:str) -> "vedo.TetMesh":
def loadNeutral(filename: Union[str, os.PathLike]) -> "vedo.TetMesh":
"""
Reads a `Neutral` tetrahedral file format.

Returns an `TetMesh` object.
"""
filename = str(filename)
with open(filename, "r", encoding="UTF-8") as f:
lines = f.readlines()

Expand All @@ -804,8 +817,9 @@ def loadNeutral(filename:str) -> "vedo.TetMesh":
return vedo.TetMesh([coords, idolf_tets])

########################################################################
def loadGmesh(filename: str) -> Mesh:
def loadGmesh(filename: Union[str, os.PathLike]) -> Mesh:
"""Reads a `gmesh` file format. Return an `Mesh` object."""
filename = str(filename)
with open(filename, "r", encoding="UTF-8") as f:
lines = f.readlines()

Expand Down Expand Up @@ -837,12 +851,13 @@ def loadGmesh(filename: str) -> Mesh:
return Mesh(poly)

########################################################################
def loadPCD(filename: str) -> Points:
def loadPCD(filename: Union[str, os.PathLike]) -> Points:
"""Return a `Mesh` made of only vertex points
from the `PointCloud` library file format.

Returns an `Points` object.
"""
filename = str(filename)
with open(filename, "r", encoding="UTF-8") as f:
lines = f.readlines()

Expand Down Expand Up @@ -982,8 +997,9 @@ def _from_numpy(d: dict) -> Mesh:
return msh

#############################################################################
def _import_npy(fileinput: str) -> "vedo.Plotter":
def _import_npy(fileinput: Union[str, os.PathLike]) -> "vedo.Plotter":
"""Import a vedo scene from numpy format."""
filename = str(fileinput)
Copy link
Contributor

@coderabbitai coderabbitai bot Aug 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove the unused variable filename.

The variable filename is assigned but never used, which is unnecessary.

-    filename = str(fileinput)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _import_npy(fileinput: Union[str, os.PathLike]) -> "vedo.Plotter":
"""Import a vedo scene from numpy format."""
filename = str(fileinput)
def _import_npy(fileinput: Union[str, os.PathLike]) -> "vedo.Plotter":
"""Import a vedo scene from numpy format."""
Tools
Ruff

1002-1002: Local variable filename is assigned to but never used

Remove assignment to unused variable filename

(F841)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a typo here, the correct line is fileinput = str(fileinput). Corrected in the following commit

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Louis-Pujol, thanks for pointing out the typo. I've noted the correct usage of fileinput = str(fileinput) for future reference.


Learnings added
Learnt from: Louis-Pujol
PR: marcomusy/vedo#1176
File: vedo/file_io.py:0-0
Timestamp: 2024-08-13T07:36:55.144Z
Learning: In the `_import_npy` function, the correct line is `fileinput = str(fileinput)`, not `filename = str(fileinput)`.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


fileinput = download(fileinput, verbose=False, force=True)
if fileinput.endswith(".npy"):
Expand Down Expand Up @@ -1113,8 +1129,9 @@ def _import_npy(fileinput: str) -> "vedo.Plotter":
return plt

###########################################################
def loadImageData(filename: str) -> Union[vtki.vtkImageData, None]:
def loadImageData(filename: Union[str, os.PathLike]) -> Union[vtki.vtkImageData, None]:
"""Read and return a `vtkImageData` object from file."""
filename = str(filename)
if ".tif" in filename.lower():
reader = vtki.new("TIFFReader")
# print("GetOrientationType ", reader.GetOrientationType())
Expand Down Expand Up @@ -1145,14 +1162,15 @@ def loadImageData(filename: str) -> Union[vtki.vtkImageData, None]:
return reader.GetOutput()

###########################################################
def write(objct: Any, fileoutput: str, binary=True) -> Any:
def write(objct: Any, fileoutput: Union[str, os.PathLike], binary=True) -> Any:
"""
Write object to file. Same as `save()`.

Supported extensions are:

- `vtk, vti, ply, obj, stl, byu, vtp, vti, mhd, xyz, xml, tif, png, bmp`
"""
fileoutput = str(fileoutput)
obj = objct.dataset

try:
Expand Down Expand Up @@ -1333,7 +1351,7 @@ def read(obj: Any, unpack=True, force=False) -> Any:
return load(obj, unpack, force)

###############################################################################
def export_window(fileoutput: str, binary=False, plt=None) -> "vedo.Plotter":
def export_window(fileoutput: Union[str, os.PathLike], binary=False, plt=None) -> "vedo.Plotter":
"""
Exporter which writes out the rendered scene into an HTML, X3D or Numpy file.

Expand All @@ -1348,6 +1366,7 @@ def export_window(fileoutput: str, binary=False, plt=None) -> "vedo.Plotter":
the rendering window can also be exported to `numpy` file `scene.npz`
by pressing `E` key at any moment during visualization.
"""
fileoutput = str(fileoutput)
if plt is None:
plt = vedo.plotter_instance

Expand Down Expand Up @@ -1594,6 +1613,8 @@ def _fillcommon(obj, adict):

#########################################################################
def _export_npy(plt, fileoutput="scene.npz") -> None:

fileoutput = str(fileoutput)

sdict = {}
sdict["shape"] = plt.shape
Expand Down Expand Up @@ -1672,13 +1693,15 @@ def _export_npy(plt, fileoutput="scene.npz") -> None:


########################################################################
def import_window(fileinput: str) -> Union["vedo.Plotter", None]:
def import_window(fileinput: Union[str, os.PathLike]) -> Union["vedo.Plotter", None]:
"""
Import a whole scene from a Numpy NPZ file.

Returns:
`vedo.Plotter` instance
"""
fileinput = str(fileinput)

if fileinput.endswith(".npy") or fileinput.endswith(".npz"):
return _import_npy(fileinput)

Expand All @@ -1694,7 +1717,7 @@ def import_window(fileinput: str) -> Union["vedo.Plotter", None]:
return None


def load_obj(fileinput: str, mtl_file=None, texture_path=None) -> List[Mesh]:
def load_obj(fileinput: Union[str, os.PathLike], mtl_file=None, texture_path=None) -> List[Mesh]:
"""
Import a set of meshes from a OBJ wavefront file.

Expand All @@ -1707,6 +1730,8 @@ def load_obj(fileinput: str, mtl_file=None, texture_path=None) -> List[Mesh]:
Returns:
`list(Mesh)`
"""
fileinput = str(fileinput)

window = vtki.vtkRenderWindow()
window.SetOffScreenRendering(1)
renderer = vtki.vtkRenderer()
Expand Down Expand Up @@ -1756,6 +1781,7 @@ def screenshot(filename="screenshot.png", scale=1, asarray=False) -> Union["vedo
asarray : (bool)
Return a numpy array of the image
"""
filename = str(filename)
# print("calling screenshot", filename, scale, asarray)

if not vedo.plotter_instance or not vedo.plotter_instance.window:
Expand All @@ -1770,7 +1796,6 @@ def screenshot(filename="screenshot.png", scale=1, asarray=False) -> Union["vedo
narr = np.flip(narr, axis=0)
return narr ##########

filename = str(filename)

if filename.endswith(".pdf"):
writer = vtki.new("GL2PSExporter")
Expand Down Expand Up @@ -1913,7 +1938,7 @@ def __init__(self, name="movie.mp4", duration=None, fps=24, scale=1, backend="im
Program `ffmpeg` is used to create video from each generated frame.

Arguments:
name : (str)
name : (Union[str, os.PathLike])
name of the output file.
duration : (float)
set the total `duration` of the video and recalculates `fps` accordingly.
Expand All @@ -1929,7 +1954,7 @@ def __init__(self, name="movie.mp4", duration=None, fps=24, scale=1, backend="im

![](https://user-images.githubusercontent.com/32848391/50739007-2bfc2b80-11da-11e9-97e6-620a3541a6fa.jpg)
"""
self.name = name
self.name = str(name)
self.duration = duration
self.backend = backend
self.fps = float(fps)
Expand Down