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__ = '20230327-1214' __citation__ = ''' @inproceedings{iclr-2023, author = {White, Jerome and Agrawal, Chandan and Ojha, Anmol and Agnihotri, Apoorv and Sharma, Makkunda and Doshi, Jigar}, title = {{BOLLWM}: A real-world dataset for bollworm pest monitoring from cotton fields in {India}}, booktitle = {International Conference on Learning Representations}, year = {2023}, series = {ICLR}, publisher = {Workshop on Practical Machine Learning for Developing Countries}, doi = {10.48550/arXiv.2304.00763}, } ''' 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