File size: 1,880 Bytes
b4e82af | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | #!/usr/bin/env python3
"""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())
|