pest-management-opendata / pest_management_opendata.py
jerome-ai's picture
Initial script for bollworm data
c973ce8
raw
history blame
4.47 kB
import itertools as it
import collections as cl
from base64 import b64encode
from pathlib import Path
from dataclasses import dataclass, asdict
from urllib.parse import urlparse, urlunparse
import cv2
import boto3
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, region_name='ap-south-1')
s3.download_file(remote.netloc, str(name), path)
@property
def labels(self):
df = wr.s3.read_csv(self.url('dev'), 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=path)
return urlunparse(source)
#
#
#
class ExampleManager:
_decode_flags = cv2.IMREAD_COLOR | cv.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):
for i in df.dropna().itertuples(index=False):
geometry = loads(i.geometry)
yield {
'label': i.label,
'geometry': geometry.wkb,
}
@staticmethod
def load(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)
def __init__(self, payload):
self.payload = payload
def __iter__(self):
df = self.payload.to_frame()
for (i, g) in df.groupby('image', sort=False):
image = self.load(urlparse(i))
pests = self.pests(g)
yield {
'image': image,
'pests': list(pests),
}
#
#
#
class WadhwaniBollwormData(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)
def _generate_examples(self, **kwargs):
payload = SplitPayload(**kwargs)
examples = ExampleManager(payload)
yield from examples