Skip to content

Commit

Permalink
Fix: Avoid exception in .xbin file is missing
Browse files Browse the repository at this point in the history
  • Loading branch information
ashvardanian committed Jul 21, 2023
1 parent 6f25ed9 commit 4863bea
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions python/usearch/io.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import os
import struct
import typing

import numpy as np


def load_matrix(
filename: str, start_row: int = 0, count_rows: int = None, view: bool = False
) -> np.ndarray:
filename: str,
start_row: int = 0,
count_rows: int = None,
view: bool = False,
) -> typing.Optional[np.ndarray]:
"""Read *.ibin, *.bbib, *.hbin, *.fbin, *.dbin files with matrices.
:param filename: path to the matrix file
Expand Down Expand Up @@ -36,18 +41,28 @@ def load_matrix(
else:
raise Exception("Unknown file type")

if not os.path.exists(filename):
return None

with open(filename, "rb") as f:
rows, cols = np.fromfile(f, count=2, dtype=np.int32)
rows = (rows - start_row) if count_rows is None else count_rows
row_offset = start_row * scalar_size * cols

if view:
return np.memmap(
f, dtype=dtype, mode="r", offset=8 + row_offset, shape=(rows, cols)
f,
dtype=dtype,
mode="r",
offset=8 + row_offset,
shape=(rows, cols),
)
else:
return np.fromfile(
f, count=rows * cols, dtype=dtype, offset=row_offset
f,
count=rows * cols,
dtype=dtype,
offset=row_offset,
).reshape(rows, cols)


Expand Down

0 comments on commit 4863bea

Please sign in to comment.