from collections import defaultdict import dataclasses from dataclasses import dataclass, field from itertools import chain import json from pathlib import Path from typing import Iterable, Literal from torch.utils.data import Dataset @dataclass class JsonlEntry: id: int split: Literal['train', 'test'] modality: Literal['google', 'satellite', 'street', 'drone'] path: str angle: int | None = None @dataclass class DatasetEntry: id: int | None = None satellite: str | None = None drone_30: str | None = None drone_45: str | None = None street: list[str] = field(default_factory=list) google: list[str] = field(default_factory=list) def update(self, entry: JsonlEntry) -> None: if self.id is None: self.id = entry.id else: if self.id != entry.id: raise ValueError(f'unmatched id {self.id=} != {entry.id=}') path = entry.path match entry.modality: case 'street': self.street.append(path) case 'google': self.google.append(path) case 'satellite': self.satellite = path case 'drone': if entry.angle == 30: self.drone_30 = path elif entry.angle == 45: self.drone_45 = path else: raise ValueError(f'unexpected angle: {entry.angle}') case _: raise ValueError(f'unexpected modality: {entry.modality}') def read_all_entries(index: Path): with index.open('r') as f: for line in f: yield json.loads(line.strip()) def get_indecies(root: Path, split: Literal['train', 'test']) -> list[Path]: index_path = root / 'meta' / 'index' res = sorted(index_path.glob(f'{split}-shard*.jsonl')) if len(res) == 0: raise ValueError('no index file found') return res def collect(indecies: Iterable[Path]): res = defaultdict(DatasetEntry) for entryobj in chain(*map(read_all_entries, indecies)): assert isinstance(entryobj, dict) entry = JsonlEntry(**entryobj) res[entry.id].update(entry) return res class V2BDemoDataset(Dataset): def __init__(self, root: str | Path, split: Literal['train', 'test']) -> None: super().__init__() self.root = Path(root) self.split = split self.index = collect(get_indecies(self.root, self.split)) self.ids = sorted(self.index.keys()) def __getitem__(self, index): building_id = self.ids[index] entry = self.index[building_id] return dataclasses.asdict(entry) def __len__(self): return len(self.ids) def main(): ds = V2BDemoDataset(Path('../'), 'train') print(ds[0]) print(len(ds)) if __name__ == '__main__': main()