File size: 5,234 Bytes
b7accb9
c973ce8
 
 
 
b7accb9
c973ce8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4879320
e389fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c973ce8
 
d438932
 
b7accb9
 
 
d438932
 
 
 
c973ce8
b7accb9
 
 
 
 
 
 
 
 
10eee64
b7accb9
 
 
 
 
10eee64
b7accb9
 
 
 
 
 
 
 
 
 
c973ce8
 
 
d438932
 
 
 
 
 
 
 
 
 
 
c973ce8
 
 
 
 
 
 
 
 
 
 
 
b7accb9
 
c973ce8
 
 
 
 
 
 
 
d438932
b7accb9
d438932
 
 
c973ce8
d438932
c973ce8
 
d438932
 
 
 
b7accb9
d438932
 
c973ce8
d438932
c973ce8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e40859e
 
 
 
 
 
 
 
2cbb899
 
 
 
d438932
 
 
 
2cbb899
d438932
 
 
 
 
2cbb899
 
d438932
c973ce8
 
 
 
c802914
c973ce8
 
 
 
 
 
 
 
 
e389fcd
c973ce8
 
 
 
 
 
 
f7186be
c973ce8
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
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