Datasets:
File size: 5,044 Bytes
4826012 b466c14 4826012 b466c14 4826012 | 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | #!/usr/bin/env python3
"""Verify OneSearch-MI images and prepare ordered inference inputs."""
import argparse
import csv
import json
import struct
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.parse import quote, urlsplit
def relative_file(root, value):
path = Path(value)
if path.is_absolute() or ".." in path.parts or "\\" in value:
raise ValueError(f"Expected a relative image path: {value}")
resolved = (root / path).resolve()
if not resolved.is_relative_to(root.resolve()) or not resolved.is_file():
raise ValueError(f"Missing image or path outside the dataset: {value}")
return resolved
def load_rows(root):
rows = [json.loads(line) for line in (root / "test.jsonl").read_text(encoding="utf-8").splitlines() if line.strip()]
if not rows or len({row["id"] for row in rows}) != len(rows):
raise ValueError("Sample IDs must be unique and the dataset must be nonempty")
for row in rows:
if (not isinstance(row["id"], str) or not row["id"].isdigit()
or str(int(row["id"])) != row["id"]):
raise ValueError("Sample IDs must be canonical nonnegative integer strings")
if any(not isinstance(row[key], str) or not row[key].strip() for key in ("question", "answer")):
raise ValueError("Question and answer must be nonempty strings")
images = row["images"]
if not isinstance(images, list) or len(images) < 2:
raise ValueError("Each MI sample must contain at least two ordered image paths")
if type(row["n_images"]) is not int or row["n_images"] != len(images):
raise ValueError("n_images must equal the length of images")
for image in images:
relative_file(root, image)
return rows
def prepare(root, rows, base_url, workers, verify_only=False):
media = [json.loads(line) for line in (root / "media.jsonl").read_text(encoding="utf-8").splitlines() if line.strip()]
inventory = {row["path"]: row for row in media}
if len(inventory) != len(media):
raise ValueError("Media inventory paths must be unique")
referenced = {path for row in rows for path in row["images"]}
if referenced != set(inventory):
raise ValueError("Media inventory must match the referenced image set")
def check(relative):
path = relative_file(root, relative)
info = inventory[relative]
if path.stat().st_size != info["bytes"]:
raise ValueError(f"Image byte size mismatch: {relative}")
with path.open("rb") as handle:
header = handle.read(24)
if (len(header) != 24 or header[:8] != b"\x89PNG\r\n\x1a\n"
or header[12:16] != b"IHDR"
or struct.unpack(">II", header[16:24]) != (info["width"], info["height"])):
raise ValueError(f"PNG dimensions differ from media.jsonl: {relative}")
with ThreadPoolExecutor(max_workers=workers) as pool:
list(pool.map(check, sorted(referenced)))
result = {"samples": len(rows), "images": len(referenced), "verified": True}
if verify_only:
return result
runtime = root / "runtime"
runtime.mkdir(parents=True, exist_ok=True)
with (runtime / "mi.csv").open("w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=["index", "question", "answer"])
writer.writeheader()
writer.writerows({"index": row["id"], "question": row["question"], "answer": row["answer"]} for row in rows)
with (runtime / "mi_manifest.jsonl").open("w", encoding="utf-8") as handle:
for row in rows:
record = {
"case_id": row["id"], "ok": True, "modality": "multi_image",
"n_images": len(row["images"]),
"image_urls": [base_url.rstrip("/") + "/" + quote(path, safe="/") for path in row["images"]],
}
handle.write(json.dumps(record) + "\n")
result["manifest"] = "runtime/mi_manifest.jsonl"
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--data-root", type=Path, default=Path(__file__).resolve().parent)
parser.add_argument("--media-base-url", help="HTTP(S) base URL serving this MI dataset directory")
parser.add_argument("--workers", type=int, default=4)
parser.add_argument("--verify-only", action="store_true")
args = parser.parse_args()
if args.workers < 1:
parser.error("--workers must be positive")
if not args.verify_only:
parsed = urlsplit(args.media_base_url or "")
if parsed.scheme not in ("http", "https") or not parsed.netloc or parsed.query or parsed.fragment or parsed.username:
parser.error("--media-base-url must be an HTTP(S) directory URL without credentials, query or fragment")
root = args.data_root.resolve()
print(json.dumps(prepare(root, load_rows(root), args.media_base_url, args.workers, args.verify_only)))
if __name__ == "__main__":
main()
|