import itertools as it import collections as cl from pathlib import Path from dataclasses import dataclass, asdict from urllib.parse import urlparse, urlunparse import pandas as pd import awswrangler as wr 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}"')) @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 AmazonStorageStyleAccess: def __init__(self, url): self.url = url def __str__(self): return urlunparse(self.url) class StandardStyleAccess(AmazonStorageStyleAccess): pass class VirtualStyleAccess(AmazonStorageStyleAccess): _region = 'ap-south-1' def __init__(self, url): parts = [ url.netloc, url.scheme, self._region, 'amazonaws', 'com', ] netloc = '.'.join(parts) url = url._replace(scheme='https', netloc=netloc) super().__init__(url) # # # class SplitManager: _splits = tuple(it.starmap(SplitInfo, ( (Split.TRAIN, 'dev', 'train'), (Split.VALIDATION, 'dev', 'val'), (Split.TEST, 'test', 'test'), ))) @property def labels(self): path = StandardStyleAccess(self.metaname('dev')) df = wr.s3.read_csv(str(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) url = VirtualStyleAccess(name) info = Path(dl_manager.download(str(url))) 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(): url = VirtualStyleAccess(urlparse(i)) yield (i, str(url)) 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