File size: 9,675 Bytes
ce88b75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""
Visualize ft_qwen35 data preprocessing: polygon outlines + char span highlights.

For each sample, draws:
  - Left: original image with polygon outlines (one color per instance, reading order)
  - Right: grounding text with char spans highlighted in matching colors
  - Bottom: formatted target text (normalized coords + spans)

Usage:
    /opt/conda/bin/python scripts/visualize_preprocessing.py \
        --dataset refcoco --split val --num_samples 5 --seed 42

    /opt/conda/bin/python scripts/visualize_preprocessing.py \
        --dataset coconut_pancap --split val --num_samples 3

    /opt/conda/bin/python scripts/visualize_preprocessing.py \
        --dataset coconut_pos_neg --split val --num_samples 3
"""

import argparse
import logging
import sys
import os

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.colors import to_rgb
from PIL import Image, ImageDraw

sys.path.insert(0, "/weka-mm/royg/ground_olmo")
sys.path.insert(0, "/weka-mm/royg/ft_qwen3_5")

from ft_qwen35.data.dataset import GroundingSourceDataset, make_random_state
from ft_qwen35.data.formatter import extract_instance_polygons, format_target_text, subsample_polygon
from ft_qwen35.config import FTQwen35Config

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)

# Distinct colors for up to ~20 instances
COLORS = [
    "#e6194b", "#3cb44b", "#ffe119", "#4363d8", "#f58231",
    "#911eb4", "#42d4f4", "#f032e6", "#bfef45", "#fabed4",
    "#469990", "#dcbeff", "#9A6324", "#800000", "#aaffc3",
    "#808000", "#ffd8b1", "#000075", "#a9a9a9", "#ffffff",
]


def draw_polygons_on_image(pil_image, instances_data, instance_order, max_poly_points=0):
    """Draw polygon outlines on image, one color per instance in reading order.

    Uses subsampled points (matching target text) when max_poly_points > 0.
    Also draws dots at each polygon vertex to show the actual sampled points.
    """
    img = pil_image.copy()
    draw = ImageDraw.Draw(img)

    legend = []  # (color, label)
    for rank, idx in enumerate(instance_order):
        if idx >= len(instances_data):
            continue
        inst = instances_data[idx]
        polygons = inst.get("polygons", [])
        char_spans = inst.get("char_spans", [])
        color = COLORS[rank % len(COLORS)]

        for poly_points in polygons:
            if len(poly_points) < 3:
                continue
            # Apply same subsampling as format_target_text
            if max_poly_points > 0:
                poly_points = subsample_polygon(poly_points, max_poly_points)

            # Draw polygon outline
            flat = []
            for x, y in poly_points:
                flat.extend([x, y])
            # Close the polygon
            flat.extend([poly_points[0][0], poly_points[0][1]])
            draw.line(flat, fill=color, width=3)

            # Draw dots at each vertex
            dot_r = 4
            for x, y in poly_points:
                draw.ellipse([x - dot_r, y - dot_r, x + dot_r, y + dot_r], fill=color)

        n_pts = sum(len(subsample_polygon(p, max_poly_points) if max_poly_points > 0 else p)
                     for p in inst.get("polygons", []))
        span_str = ", ".join(f"[{s}:{e}]" for s, e in char_spans)
        legend.append((color, f"inst {idx} ({n_pts} pts, spans: {span_str})"))

    return img, legend


def render_colored_text(ax, grounding_text, instances_data, instance_order):
    """Render grounding text with char spans highlighted in instance colors."""
    # Build a color map: char_index -> color
    char_colors = [None] * len(grounding_text)
    for rank, idx in enumerate(instance_order):
        if idx >= len(instances_data):
            continue
        inst = instances_data[idx]
        color = COLORS[rank % len(COLORS)]
        for s, e in inst.get("char_spans", []):
            for ci in range(s, min(e, len(grounding_text))):
                char_colors[ci] = color

    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    ax.axis("off")

    # Render text with colored backgrounds, wrapping lines
    fontsize = 12
    x, y = 0.02, 0.92
    line_height = 0.06
    char_width = 0.012  # approximate monospace width

    for i, ch in enumerate(grounding_text):
        if x > 0.95:
            x = 0.02
            y -= line_height
            if y < 0.02:
                break

        bg = char_colors[i]
        if bg:
            ax.text(x, y, ch, fontsize=fontsize, family="monospace",
                    va="top", ha="left",
                    bbox=dict(boxstyle="round,pad=0.05", facecolor=bg, alpha=0.7, edgecolor="none"))
        else:
            ax.text(x, y, ch, fontsize=fontsize, family="monospace",
                    va="top", ha="left", color="black")
        x += char_width


def visualize_sample(example, sample_idx, dataset_name, output_dir, config):
    """Visualize one preprocessed sample."""
    image_path = example.get("image")
    if image_path is None:
        logger.warning(f"Sample {sample_idx}: no image path, skipping")
        return

    category_name = example.get("category_name", "")
    instances = example.get("instances", [])
    instance_order = example.get("instance_order", list(range(len(instances))))
    char_spans = example.get("char_spans_per_instance", [])

    # Open original image
    pil_image = Image.open(image_path).convert("RGB")
    orig_w, orig_h = pil_image.size

    # Extract polygons (same as preprocessor)
    instances_data = []
    for i, inst in enumerate(instances):
        polygons, source = extract_instance_polygons(inst)
        inst_char_spans = char_spans[i] if i < len(char_spans) else []
        instances_data.append({
            "polygons": polygons,
            "char_spans": inst_char_spans,
            "polygon_source": source,
        })

    # Format target text (same as preprocessor)
    target_text = format_target_text(
        instances_data=instances_data,
        instance_order=instance_order,
        orig_h=orig_h,
        orig_w=orig_w,
        coord_range=config.coord_range,
        max_poly_points=config.max_poly_points,
    )

    # Draw polygons on image (with same subsampling as target text)
    annotated_img, legend = draw_polygons_on_image(
        pil_image, instances_data, instance_order, max_poly_points=config.max_poly_points
    )

    # Create figure
    n_instances = len([i for i in instance_order if i < len(instances_data)])
    fig = plt.figure(figsize=(18, 10))

    # Top-left: annotated image
    ax_img = fig.add_axes([0.02, 0.30, 0.50, 0.65])
    ax_img.imshow(np.array(annotated_img))
    ax_img.set_title(f"{dataset_name} idx={sample_idx}  ({orig_w}x{orig_h}, {n_instances} instances)",
                     fontsize=11)
    ax_img.axis("off")

    # Top-right: grounding text with colored char spans
    ax_text = fig.add_axes([0.54, 0.30, 0.44, 0.65])
    ax_text.set_title("Grounding text (char spans highlighted)", fontsize=11)
    render_colored_text(ax_text, category_name, instances_data, instance_order)

    # Legend
    handles = []
    for color, label in legend:
        handles.append(mpatches.Patch(color=color, label=label))
    if handles:
        ax_text.legend(handles=handles, loc="lower left", fontsize=8, ncol=1)

    # Bottom: target text (full, no truncation)
    # Estimate height needed: ~1 line per instance + header
    target_lines = target_text.split("\n")
    n_target_lines = len(target_lines)
    # Each line needs ~0.025 of figure height at fontsize 7
    target_height = max(0.25, min(0.55, 0.04 + n_target_lines * 0.025))
    # Adjust figure: shift image/text panels up, expand bottom
    fig.set_size_inches(18, 10 + max(0, (target_height - 0.25) * 10))

    ax_target = fig.add_axes([0.02, 0.02, 0.96, target_height])
    ax_target.axis("off")
    ax_target.text(0.0, 1.0, f"Target text ({n_target_lines} lines):\n{target_text}",
                   fontsize=7, family="monospace", va="top", ha="left",
                   transform=ax_target.transAxes)

    out_path = os.path.join(output_dir, f"{dataset_name}_{sample_idx:04d}.png")
    fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor="white")
    plt.close(fig)
    logger.info(f"Saved: {out_path}")


def main():
    parser = argparse.ArgumentParser(description="Visualize ft_qwen35 preprocessing")
    parser.add_argument("--dataset", type=str, default="refcoco",
                        help="Dataset name from DATASET_REGISTRY")
    parser.add_argument("--split", type=str, default="val")
    parser.add_argument("--num_samples", type=int, default=5)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--output_dir", type=str, default="data/vis")
    parser.add_argument("--max_poly_points", type=int, default=64)
    parser.add_argument("--start_idx", type=int, default=0)
    args = parser.parse_args()

    os.makedirs(args.output_dir, exist_ok=True)

    config = FTQwen35Config(max_poly_points=args.max_poly_points)

    logger.info(f"Loading {args.dataset} ({args.split})...")
    ds = GroundingSourceDataset(args.dataset, split=args.split)
    logger.info(f"Dataset size: {len(ds)}")

    n = min(args.num_samples, len(ds) - args.start_idx)
    for i in range(n):
        idx = args.start_idx + i
        rng = make_random_state(args.seed, idx, 0, 1)
        try:
            example = ds.get(idx, rng)
            visualize_sample(example, idx, args.dataset, args.output_dir, config)
        except Exception as e:
            logger.error(f"Failed on sample {idx}: {e}")


if __name__ == "__main__":
    main()