File size: 7,490 Bytes
3178059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""One record is one image/query condition; a unit is one native item or pair."""
from pathlib import Path
import json
import math

import numpy as np
from PIL import Image


def decode_rle(rle):
    """Decode COCO compressed or uncompressed RLE to a bool [height, width] mask."""
    counts = rle['counts']
    if isinstance(counts, str):
        decoded = []
        pos = 0
        while pos < len(counts):
            value = 0
            shift = 0
            while True:
                if pos >= len(counts):
                    raise ValueError('Truncated COCO RLE')
                code = ord(counts[pos]) - 48
                pos += 1
                if not 0 <= code <= 63:
                    raise ValueError('Invalid COCO RLE character')
                value |= (code & 31) << shift
                shift += 5
                if not code & 32:
                    if code & 16:
                        value |= -1 << shift
                    break
            if len(decoded) > 2:
                value += decoded[-2]
            decoded.append(value)
        counts = decoded
    height, width = map(int, rle['size'])
    counts = [int(v) for v in counts]
    if height <= 0 or width <= 0 or any(v < 0 for v in counts) or sum(counts) != height * width:
        raise ValueError('RLE runs do not match image dimensions')
    flat = np.zeros(height * width, dtype=bool)
    offset = 0
    for idx, length in enumerate(counts):
        if idx % 2:
            flat[offset:offset + length] = True
        offset += length
    return flat.reshape((height, width), order='F')


class Dataset:
    """Read normalized catalogs and frozen selections without dataset-specific code.

    iter_samples() defaults to selected primary conditions. For HalluSegBench,
    get_pair() exposes the four image/query combinations. References are kept
    separate from the image/question returned by model_input().
    """

    def __init__(self, root='prepared_data'):
        self.root = Path(root).resolve()
        self.report = json.loads((self.root / 'build_report.json').read_text())
        if self.report['schema_version'] != 1 or self.report['status'] != 'complete':
            raise ValueError('Unsupported or incomplete prepared dataset')
        self._records = {}
        self._datasets = {}
        self._pairs = {}
        self._selections = {}
        for name in self.report['datasets']:
            path = self.root / 'manifests' / (name + '.jsonl')
            samples = [json.loads(line) for line in path.read_text().splitlines() if line]
            self._datasets[name] = samples
            self._selections[name] = json.loads((self.root / 'selections' / (name + '.json')).read_text())
            for sample in samples:
                if sample['sample_id'] in self._records:
                    raise ValueError('Duplicate sample ID: ' + sample['sample_id'])
                self._records[sample['sample_id']] = sample
                if sample['pair_id']:
                    self._pairs.setdefault(sample['pair_id'], {})[sample['condition']] = sample

    def get(self, sample_id):
        return self._records[sample_id]

    def get_pair(self, sample_or_pair_id):
        pair_id = (sample_or_pair_id.get('pair_id') if isinstance(sample_or_pair_id, dict)
                   else sample_or_pair_id)
        if pair_id in self._records:
            pair_id = self._records[pair_id]['pair_id']
        if not pair_id:
            raise ValueError('This sample has no counterfactual pair')
        return dict(self._pairs[pair_id])

    def iter_samples(self, dataset=None, subset='selected', condition='primary'):
        """subset: selected/test/development/all; condition: primary/all/exact name."""
        if subset not in {'selected', 'test', 'development', 'all'}:
            raise ValueError('Unknown subset: ' + subset)
        names = [dataset] if dataset else list(self._datasets)
        for name in names:
            selection = self._selections[name]
            allowed = None if subset == 'all' else set(selection[subset + '_unit_ids'])
            for sample in self._datasets[name]:
                if allowed is not None and sample['unit_id'] not in allowed:
                    continue
                if condition == 'primary' and not sample['is_primary']:
                    continue
                if condition not in {'primary', 'all'} and sample['condition'] != condition:
                    continue
                yield sample

    def _path(self, relative):
        path = (self.root / relative).resolve()
        if not path.is_relative_to(self.root):
            raise ValueError('Asset path escapes prepared dataset')
        return path

    def load_image(self, sample):
        with Image.open(self._path(sample['image']['path'])) as image:
            return image.convert('RGB')

    def model_input(self, sample):
        """Only these fields go to a model; no answers, target labels, or boxes."""
        return {'image': self.load_image(sample), 'question': sample['question']}

    def reference(self, sample):
        return sample['reference']

    def boxes(self, sample):
        return [r['bbox_xyxy'] for r in sample['reference']['regions']]

    def mask(self, sample, region_index=None):
        """True target masks; returns None for bbox-only supervision.

        Empty annotated regions return an all-false mask; inspect target_status
        to distinguish absence, no match, and no annotated target. Bbox-only
        positives and unavailable annotations return None.
        """
        regions = sample['reference']['regions']
        height, width = sample['image']['height'], sample['image']['width']
        if sample['reference']['region_kind'] == 'unavailable':
            return None
        if not regions:
            return np.zeros((height, width), dtype=bool)
        if any(r['mask'] is None for r in regions):
            return None
        use = regions if region_index is None else [regions[region_index]]
        merged = np.zeros((height, width), dtype=bool)
        for region in use:
            spec = region['mask']
            if spec['encoding'] == 'coco_rle':
                mask = decode_rle(spec)
            elif spec['encoding'] == 'binary_png':
                with Image.open(self._path(spec['path'])) as image:
                    mask = np.asarray(image.convert('L')) > 0
            else:
                raise ValueError('Unknown mask encoding')
            if mask.shape != merged.shape:
                raise ValueError('Mask size does not match this image')
            merged |= mask
        return merged

    def region_mask(self, sample):
        """Rasterized annotated regions for attention: mask if present, else bbox.

        Read reference.region_kind when aggregating scores; bbox rasterization
        is not a segmentation annotation. Floating boxes use pixel-center tests.
        """
        mask = self.mask(sample)
        if mask is not None:
            return mask
        if sample['reference']['region_kind'] == 'unavailable':
            return None
        h, w = sample['image']['height'], sample['image']['width']
        out = np.zeros((h, w), dtype=bool)
        for x1, y1, x2, y2 in self.boxes(sample):
            left, right = max(0, math.ceil(x1 - .5)), min(w, math.ceil(x2 - .5))
            top, bottom = max(0, math.ceil(y1 - .5)), min(h, math.ceil(y2 - .5))
            out[top:bottom, left:right] = True
        return out