binding-clip / binding_clip /download.py
Kiriti-Ray's picture
Release four BindingCLIP models, source, and evaluation
44c8862 verified
Raw History Blame Contribute Delete
6.7 kB
"""Fetch deterministic prefixes of the official CoGenT ZIP in archive order."""
import argparse
import io
import re
import shutil
import tempfile
import urllib.request
import zipfile
from collections import defaultdict
from pathlib import Path
URL = "https://dl.fbaipublicfiles.com/clevr/CLEVR_CoGenT_v1.0.zip"
SPLITS = ("trainA", "valA", "valB")
RANGE_CHUNK = 64 * 2**20
def request(start, end):
return urllib.request.urlopen(
urllib.request.Request(URL, headers={"Range": f"bytes={start}-{end - 1}"}),
timeout=90,
)
class Archive(io.RawIOBase):
def __init__(self, cache):
self.pos = 0
self.cache = cache
self.blocks = []
with request(0, 1) as response:
match = re.fullmatch(r"bytes 0-0/(\d+)", response.headers.get("Content-Range", ""))
if response.status != 206 or not match:
raise OSError("The CLEVR server did not return a byte range.")
self.size = int(match[1])
def tell(self):
return self.pos
def seek(self, offset, whence=io.SEEK_SET):
self.pos = {io.SEEK_SET: 0, io.SEEK_CUR: self.pos, io.SEEK_END: self.size}[whence] + offset
return self.pos
def read(self, size=-1):
end = self.size if size < 0 else min(self.pos + size, self.size)
left = self.pos
pieces = []
while left < end:
for start, stop, path in self.blocks:
if start <= left < stop:
with path.open("rb") as file:
file.seek(left - start)
pieces.append(file.read(min(end, stop) - left))
left = min(end, stop)
break
else:
with request(left, end) as response:
pieces.append(self.checked_read(response, left, end))
left = end
self.pos = end
return b"".join(pieces)
def checked_read(self, response, start, end, output=None):
expected = f"bytes {start}-{end - 1}/{self.size}"
if response.status != 206 or response.headers.get("Content-Range") != expected:
raise OSError(f"Expected {expected}, got {response.headers.get('Content-Range')}")
if output is None:
data = response.read()
if len(data) != end - start:
raise OSError("The CLEVR server sent an incomplete range.")
return data
shutil.copyfileobj(response, output, 1024 * 1024)
def prefetch(self, start, end):
for offset in range(start, end, RANGE_CHUNK):
stop = min(offset + RANGE_CHUNK, end)
if any(a == offset and b == stop for a, b, _ in self.blocks):
continue
path = self.cache / f"{offset}-{stop}"
if not path.exists() or path.stat().st_size != stop - offset:
for attempt in range(3):
try:
with request(offset, stop) as response, tempfile.NamedTemporaryFile(dir=self.cache) as output:
self.checked_read(response, offset, stop, output)
output.flush()
if output.tell() != stop - offset:
raise OSError("The CLEVR server sent an incomplete range.")
shutil.copyfile(output.name, path)
break
except (OSError, TimeoutError):
if attempt == 2:
raise
print(f"Downloaded {stop - offset:,} bytes at {offset:,}", flush=True)
self.blocks.append((offset, stop, path))
def fetch_subset(root, counts, validation_offset=0):
root.mkdir(parents=True, exist_ok=True)
cache = root / ".ranges"
cache.mkdir(exist_ok=True)
archive = Archive(cache)
with zipfile.ZipFile(archive) as bundle:
by_split = defaultdict(list)
scene_files = {}
entries = sorted(bundle.infolist(), key=lambda entry: entry.header_offset)
next_offset = {
item.filename: following.header_offset for item, following in zip(entries, entries[1:])
}
for item in entries:
parts = item.filename.split("/")
if len(parts) == 4 and parts[1] == "images" and parts[3].endswith(".png"):
by_split[parts[2]].append(item)
if len(parts) == 3 and parts[1] == "scenes" and parts[2].endswith("_scenes.json"):
scene_files[parts[2].split("_")[1]] = item
for split, count in zip(SPLITS, counts):
if not count:
continue
offset = 0 if split == "trainA" else validation_offset
images = by_split[split][offset:offset + count]
if len(images) != count:
raise ValueError(f"Requested images {offset}:{offset + count} but {split} has {len(by_split[split])} entries")
scene = scene_files[split]
archive.prefetch(scene.header_offset, next_offset[scene.filename])
archive.prefetch(images[0].header_offset, next_offset[images[-1].filename])
for item in [scene, *images]:
path = root.joinpath(*item.filename.split("/")[1:])
path.parent.mkdir(parents=True, exist_ok=True)
if path.exists() and path.stat().st_size == item.file_size:
continue
data = bundle.read(item)
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as temporary:
temporary.write(data)
Path(temporary.name).replace(path)
manifest = root / f"{split}.txt"
manifest.write_text("".join(Path(item.filename).name + "\n" for item in images))
print(f"{split}: {len(images):,} images and official scene annotations", flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("root", type=Path)
parser.add_argument("--train-images", type=int, default=6000)
parser.add_argument("--validation-images", type=int, default=1000)
parser.add_argument("--validation-offset", type=int, default=0)
args = parser.parse_args()
if min(args.train_images, args.validation_images, args.validation_offset) < 0:
parser.error("split sizes and validation offset must be nonnegative")
if not (args.train_images or args.validation_images):
parser.error("request at least one split")
fetch_subset(
args.root, (args.train_images, args.validation_images, args.validation_images), args.validation_offset
)
if __name__ == "__main__":
main()