"""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