Datasets:
File size: 1,012 Bytes
6a6b2e7 f2c1306 6a6b2e7 f2c1306 6a6b2e7 f2c1306 6a6b2e7 f2c1306 | 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 | """Read paired image/JSON records from a local path or an open binary stream."""
import json
import tarfile
def iter_records(source):
"""Yield (key, parts); parts contains decoded JSON and encoded image bytes."""
options = {"fileobj": source} if hasattr(source, "read") else {"name": source}
with tarfile.open(mode="r|*", **options) as archive:
current, parts = None, {}
for member in archive:
if not member.isfile():
continue
key, extension = member.name.rsplit(".", 1)
if extension not in ("json", "png", "jpg", "jpeg"):
continue
if current is not None and key != current:
yield current, parts
parts = {}
current = key
with archive.extractfile(member) as entry:
data = entry.read()
parts[extension] = json.loads(data) if extension == "json" else data
if current is not None:
yield current, parts
|