Parse an ivecs file and return a list of int32 vectors. Each vector is stored as: 4 bytes (int32 dimension) + dim * 4 bytes (int32 values) Args: filepath: Path to the .ivecs file. Returns: List of lists of ints. Raises: FileNotFoundError: If the fi
(filepath)
| 87 | |
| 88 | |
| 89 | def read_ivecs(filepath): |
| 90 | """Parse an ivecs file and return a list of int32 vectors. |
| 91 | |
| 92 | Each vector is stored as: |
| 93 | 4 bytes (int32 dimension) + dim * 4 bytes (int32 values) |
| 94 | |
| 95 | Args: |
| 96 | filepath: Path to the .ivecs file. |
| 97 | |
| 98 | Returns: |
| 99 | List of lists of ints. |
| 100 | |
| 101 | Raises: |
| 102 | FileNotFoundError: If the file does not exist. |
| 103 | ValueError: If the file format is invalid or dimensions are inconsistent. |
| 104 | """ |
| 105 | if not os.path.isfile(filepath): |
| 106 | raise FileNotFoundError(f"ivecs file not found: {filepath}") |
| 107 | |
| 108 | vectors = [] |
| 109 | expected_dim = None |
| 110 | file_size = os.path.getsize(filepath) |
| 111 | |
| 112 | with open(filepath, "rb") as f: |
| 113 | while f.tell() < file_size: |
| 114 | # Read dimension (4 bytes, int32) |
| 115 | dim_bytes = f.read(4) |
| 116 | if len(dim_bytes) < 4: |
| 117 | if len(dim_bytes) == 0: |
| 118 | break # Clean EOF |
| 119 | raise ValueError( |
| 120 | f"Unexpected end of file reading dimension at byte {f.tell() - len(dim_bytes)} " |
| 121 | f"in {filepath}" |
| 122 | ) |
| 123 | |
| 124 | (dim,) = struct.unpack("<i", dim_bytes) |
| 125 | if dim <= 0: |
| 126 | raise ValueError( |
| 127 | f"Invalid dimension {dim} at vector index {len(vectors)} in {filepath}" |
| 128 | ) |
| 129 | |
| 130 | if expected_dim is None: |
| 131 | expected_dim = dim |
| 132 | elif dim != expected_dim: |
| 133 | raise ValueError( |
| 134 | f"Dimension mismatch at vector index {len(vectors)}: " |
| 135 | f"expected {expected_dim}, got {dim} in {filepath}" |
| 136 | ) |
| 137 | |
| 138 | # Read vector data (dim * 4 bytes, int32) |
| 139 | vec_bytes = f.read(dim * 4) |
| 140 | if len(vec_bytes) < dim * 4: |
| 141 | raise ValueError( |
| 142 | f"Unexpected end of file reading vector data at vector index {len(vectors)} " |
| 143 | f"in {filepath}. Expected {dim * 4} bytes, got {len(vec_bytes)}" |
| 144 | ) |
| 145 | |
| 146 | values = list(struct.unpack(f"<{dim}i", vec_bytes)) |
no outgoing calls