import functools as ft import itertools as it import collections as cl from pathlib import Path from dataclasses import dataclass, asdict from urllib.parse import ParseResult, urlparse, urlunparse import pandas as pd from datasets import ( Split, Image, Value, Features, Sequence, ClassLabel, DatasetInfo, SplitGenerator, GeneratorBasedBuilder, ) from shapely.wkt import loads __version__ = '20220912-2056' SplitInfo = cl.namedtuple('SplitInfo', 'dtype, basename, split') Payload = cl.namedtuple('Payload', 'source, target, df') # # # def readsp(path, split): return (pd .read_csv(path, compression='gzip') .query(f'split == "{split}"')) # # # @ft.singledispatch def bucket2virtual(url): raise TypeError(type(url)) @bucket2virtual.register def _(url: ParseResult): netloc = '.'.join(( url.netloc, url.scheme, 'ap-south-1', 'amazonaws', 'com', )) return urlunparse(url._replace(scheme='https', netloc=netloc)) @bucket2virtual.register def _(url: str): return bucket2virtual(urlparse(url)) # # # @dataclass class SplitPayload: split: str metadata: Path images: dict def __iter__(self): df = readsp(self.metadata, self.split) for (i, g) in df.groupby('url', sort=False): source = urlparse(i) target = Path(self.images[i]) yield Payload(source, target, g) # # # class SplitManager: _splits = tuple(it.starmap(SplitInfo, ( (Split.TRAIN, 'dev', 'train'), (Split.VALIDATION, 'dev', 'val'), (Split.TEST, 'test', 'test'), ))) @property def labels(self): path = bucket2virtual(self.metaname('dev')) df = pd.read_csv(path, compression='gzip') yield from df['label'].dropna().unique() def __init__(self, bucket): self.bucket = bucket self.path = Path('metadata', __version__) def __call__(self, dl_manager): for i in self._splits: name = self.metaname(i.basename) info = Path(dl_manager.download(bucket2virtual(name))) images = self.images(i.split, info) ipaths = dl_manager.download(dict(images)) payload = SplitPayload(i.split, info, ipaths) yield SplitGenerator(name=i.dtype, gen_kwargs=asdict(payload)) @staticmethod def images(split, info): df = readsp(info, split) for i in df['url'].unique(): yield (i, bucket2virtual(i)) def metaname(self, split): path = self.path.joinpath(split).with_suffix('.csv.gz') return self.bucket._replace(path=str(path)) # # # class ExampleManager: # _Pest = cl.namedtuple('_Pest', 'label, geometry') # _Feature = cl.namedtuple('_Feature', 'image, pests') @staticmethod def features(labels): return Features({ 'image': Image(), 'pests': Sequence({ 'label': ClassLabel(names=labels), 'geometry': Value('binary'), }), }) @staticmethod def pests(df): if 'geometry' in df.columns: for i in df.dropna().itertuples(index=False): geometry = loads(i.geometry) yield { 'label': i.label, 'geometry': geometry.wkb, } def __init__(self, payload): self.payload = payload def __iter__(self): for i in self.payload: key = urlunparse(i.source) with i.target.open('rb') as fp: raw = fp.read() value = { 'image': { 'path': i.target, 'bytes': raw, }, 'pests': list(self.pests(i.df)), } yield (key, value) # # # class PestManagementOpendata(GeneratorBasedBuilder): _bucket = urlparse('s3://wadhwaniai-agri-opendata') def _info(self): data = SplitManager(self._bucket) labels = sorted(data.labels) features = ExampleManager.features(labels) return DatasetInfo( homepage='https://github.com/WadhwaniAI/pest-management-opendata', # citation=_CITATION, # description=_DESCRIPTION, license='CC-BY 4.0', features=features, ) def _split_generators(self, dl_manager): splits = SplitManager(self._bucket) return list(splits(dl_manager)) def _generate_examples(self, **kwargs): payload = SplitPayload(**kwargs) examples = ExampleManager(payload) yield from examples