| |
| """Read one record from a LocateAnything records.jsonl + uint64 offset index.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import struct |
| from pathlib import Path |
|
|
|
|
| U64 = struct.Struct("<Q") |
|
|
|
|
| def read_offset(index_file, position: int) -> int: |
| index_file.seek(position * U64.size) |
| raw = index_file.read(U64.size) |
| if len(raw) != U64.size: |
| raise IndexError(f"offset {position} is outside the index") |
| return U64.unpack(raw)[0] |
|
|
|
|
| def read_record(records_path: Path, row_id: int) -> dict: |
| if row_id < 0: |
| raise ValueError("row_id must be non-negative") |
| index_path = records_path.with_name(records_path.name + ".idx") |
| index_bytes = index_path.stat().st_size |
| if index_bytes % U64.size != 0 or index_bytes < 2 * U64.size: |
| raise ValueError(f"invalid uint64 offset index: {index_path}") |
| record_count = index_bytes // U64.size - 1 |
| if row_id >= record_count: |
| raise IndexError(f"row_id {row_id} outside [0, {record_count})") |
|
|
| with index_path.open("rb") as index_file: |
| start = read_offset(index_file, row_id) |
| end = read_offset(index_file, row_id + 1) |
| if end <= start: |
| raise ValueError(f"non-increasing offsets for row {row_id}: {start}, {end}") |
|
|
| with records_path.open("rb") as records_file: |
| records_file.seek(start) |
| raw = records_file.read(end - start) |
| return json.loads(raw) |
|
|
|
|
| def main() -> int: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("records_jsonl", type=Path) |
| parser.add_argument("row_id", type=int) |
| args = parser.parse_args() |
| print( |
| json.dumps( |
| read_record(args.records_jsonl, args.row_id), |
| ensure_ascii=False, |
| indent=2, |
| sort_keys=True, |
| ) |
| ) |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|