Datasets:
File size: 2,882 Bytes
5e8ce4c |
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 108 109 |
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()
|