import itertools as it import collections as cl from pathlib import Path from dataclasses import dataclass, asdict from urllib.parse import urlparse, urlunparse import cv2 import boto3 import numpy as np 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') @dataclass class SplitPayload: split: str path: Path def __post_init__(self): self.path = Path(self.path) def to_frame(self): return (pd .read_csv(self.path, compression='gzip') .query(f'split == "{self.split}"')) # # # class SplitManager: _splits = tuple(it.starmap(SplitInfo, ( (Split.TRAIN, 'dev', 'train'), (Split.VALIDATION, 'dev', 'val'), (Split.TEST, 'test', 'test'), ))) @staticmethod def custom_download(url, path): remote = urlparse(url) name = Path(remote.path) if name.is_absolute(): name = name.relative_to(name.parents[-1]) s3 = boto3.client(remote.scheme) s3.download_file(remote.netloc, str(name), path) @property def labels(self): path = self.url('dev') df = wr.s3.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: url = self.url(i.basename) path = dl_manager.download_custom(url, self.custom_download) payload = SplitPayload(i.split, path) yield SplitGenerator(name=i.dtype, gen_kwargs=asdict(payload)) def url(self, split): path = self.path.joinpath(split).with_suffix('.csv.gz') source = self.bucket._replace(path=str(path)) return urlunparse(source) # # # class ExampleManager: _decode_flags = cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION # _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): df = self.payload.to_frame() for (i, g) in df.groupby('url', sort=False): value = { 'image': self.load(urlparse(i)), 'pests': list(self.pests(g)), } yield (i, value) def load(self, url): path = Path(url.path) if path.is_absolute(): (*_, root) = path.parents path = path.relative_to(root) data = (boto3 .resource(url.scheme) .Bucket(url.netloc) .Object(str(path)) .get() .get('Body') .read()) image = np.asarray(bytearray(data)) return cv2.imdecode(image, self._decode_flags) # # # 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