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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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Utility functions for Rex Omni
"""

from typing import Any, Dict, List, Optional, Tuple

import numpy as np
from PIL import Image, ImageDraw, ImageFont


class ColorGenerator:
    """Generate consistent colors for visualization"""

    def __init__(self, color_type: str = "text"):
        self.color_type = color_type

        if color_type == "same":
            self.color = tuple((np.random.randint(0, 127, size=3) + 128).tolist())
        elif color_type == "text":
            np.random.seed(3396)
            self.num_colors = 300
            self.colors = np.random.randint(0, 127, size=(self.num_colors, 3)) + 128
        else:
            raise ValueError(f"Unknown color type: {color_type}")

    def get_color(self, text: str) -> Tuple[int, int, int]:
        """Get color for given text"""
        if self.color_type == "same":
            return self.color

        if self.color_type == "text":
            text_hash = hash(text)
            index = text_hash % self.num_colors
            color = tuple(self.colors[index])
            return color

        raise ValueError(f"Unknown color type: {self.color_type}")


def RexOmniVisualize(
    image: Image.Image,
    predictions: Dict[str, List[Dict]],
    font_size: int = 15,
    draw_width: int = 6,
    show_labels: bool = True,
    custom_colors: Optional[Dict[str, Tuple[int, int, int]]] = None,
) -> Image.Image:
    """
    Visualize predictions on image

    Args:
        image: Input image
        predictions: Predictions dictionary from RexOmniWrapper
        font_size: Font size for labels
        draw_width: Line width for drawing
        show_labels: Whether to show text labels
        custom_colors: Custom colors for categories

    Returns:
        Image with visualizations
    """
    # Create a copy of the image
    vis_image = image.copy()
    draw = ImageDraw.Draw(vis_image)

    # Load font
    font = _load_font(font_size)

    # Color generator
    color_generator = ColorGenerator("text")

    # Draw predictions for each category
    for category, annotations in predictions.items():
        # Get color for this category
        if custom_colors and category in custom_colors:
            color = custom_colors[category]
        else:
            color = color_generator.get_color(category)

        for i, annotation in enumerate(annotations):
            annotation_type = annotation.get("type", "box")
            coords = annotation.get("coords", [])

            if annotation_type == "box" and len(coords) == 4:
                _draw_box(draw, coords, color, draw_width, category, font, show_labels)
            elif annotation_type == "point" and len(coords) == 2:
                _draw_point(
                    draw, coords, color, draw_width, category, font, show_labels
                )
            elif annotation_type == "polygon" and len(coords) >= 3:
                _draw_polygon(
                    draw,
                    vis_image,
                    coords,
                    color,
                    draw_width,
                    category,
                    font,
                    show_labels,
                )
            elif annotation_type == "keypoint":
                _draw_keypoint(draw, annotation, color, draw_width, font, show_labels)

    return vis_image


def _load_font(font_size: int) -> ImageFont.ImageFont:
    """Load font for drawing"""
    font_paths = [
        "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
        "/System/Library/Fonts/Arial.ttf",
        "/System/Library/Fonts/Helvetica.ttc",
        "arial.ttf",
        "C:/Windows/Fonts/arial.ttf",
    ]

    font = None
    for font_path in font_paths:
        try:
            font = ImageFont.truetype(font_path, font_size)
            break
        except:
            continue

    if font is None:
        font = ImageFont.load_default()

    return font


def _draw_box(
    draw: ImageDraw.ImageDraw,
    coords: List[float],
    color: Tuple[int, int, int],
    draw_width: int,
    label: str,
    font: ImageFont.ImageFont,
    show_labels: bool,
):
    """Draw bounding box"""
    x0, y0, x1, y1 = [int(c) for c in coords]

    # Check valid box
    if x0 >= x1 or y0 >= y1:
        return

    # Draw rectangle
    draw.rectangle([x0, y0, x1, y1], outline=color, width=draw_width)

    # Draw label
    if show_labels and label:
        bbox = draw.textbbox((x0, y0), label, font)
        box_h = bbox[3] - bbox[1]

        y0_text = y0 - box_h - (draw_width * 2)
        y1_text = y0 + draw_width

        if y0_text < 0:
            y0_text = 0
            y1_text = y0 + 2 * draw_width + box_h

        draw.rectangle(
            [x0, y0_text, bbox[2] + draw_width * 2, y1_text],
            fill=color,
        )
        draw.text(
            (x0 + draw_width, y0_text),
            label,
            fill="black",
            font=font,
        )


def _draw_point(
    draw: ImageDraw.ImageDraw,
    coords: List[float],
    color: Tuple[int, int, int],
    draw_width: int,
    label: str,
    font: ImageFont.ImageFont,
    show_labels: bool,
):
    """Draw point"""
    x, y = [int(c) for c in coords]

    # Draw point as circle
    radius = max(8, draw_width)
    border_width = 3

    # Draw white border
    draw.ellipse(
        [
            x - radius - border_width,
            y - radius - border_width,
            x + radius + border_width,
            y + radius + border_width,
        ],
        fill="white",
        outline="white",
    )

    # Draw colored center
    draw.ellipse(
        [x - radius, y - radius, x + radius, y + radius],
        fill=color,
        outline=color,
    )

    # Draw label
    if show_labels and label:
        label_x, label_y = x + 15, y - 15
        bbox = draw.textbbox((label_x, label_y), label, font)
        box_h = bbox[3] - bbox[1]
        box_w = bbox[2] - bbox[0]

        padding = 4

        # Draw background
        draw.rectangle(
            [
                label_x - padding,
                label_y - box_h - padding,
                label_x + box_w + padding,
                label_y + padding,
            ],
            fill=color,
        )

        # Draw text
        draw.text((label_x, label_y - box_h), label, fill="white", font=font)


def _draw_polygon(
    draw: ImageDraw.ImageDraw,
    image: Image.Image,
    coords: List[List[float]],
    color: Tuple[int, int, int],
    draw_width: int,
    label: str,
    font: ImageFont.ImageFont,
    show_labels: bool,
):
    """Draw polygon"""
    # Convert to flat list for PIL
    flat_coords = []
    for point in coords:
        flat_coords.extend([int(point[0]), int(point[1])])

    # Draw polygon outline
    draw.polygon(flat_coords, outline=color, width=draw_width)

    # Draw label at first point
    if show_labels and label and coords:
        label_x, label_y = int(coords[0][0]), int(coords[0][1]) - 10
        bbox = draw.textbbox((label_x, label_y), label, font)
        box_h = bbox[3] - bbox[1]
        box_w = bbox[2] - bbox[0]

        # Draw background
        draw.rectangle(
            [
                label_x - 4,
                label_y - box_h - 4,
                label_x + box_w + 4,
                label_y,
            ],
            fill=color,
        )

        # Draw text
        draw.text((label_x, label_y - box_h - 2), label, fill="black", font=font)


def _draw_keypoint(
    draw: ImageDraw.ImageDraw,
    annotation: Dict[str, Any],
    color: Tuple[int, int, int],
    draw_width: int,
    font: ImageFont.ImageFont,
    show_labels: bool,
):
    """Draw keypoint annotation with skeleton"""
    bbox = annotation.get("bbox", [])
    keypoints = annotation.get("keypoints", {})
    instance_id = annotation.get("instance_id", "")

    # Draw bounding box
    if len(bbox) == 4:
        _draw_box(draw, bbox, color, draw_width, instance_id, font, show_labels)

    # COCO keypoint skeleton connections
    skeleton_connections = [
        # Head connections
        ("nose", "left eye"),
        ("nose", "right eye"),
        ("left eye", "left ear"),
        ("right eye", "right ear"),
        # Body connections
        ("left shoulder", "right shoulder"),
        ("left shoulder", "left elbow"),
        ("right shoulder", "right elbow"),
        ("left elbow", "left wrist"),
        ("right elbow", "right wrist"),
        ("left shoulder", "left hip"),
        ("right shoulder", "right hip"),
        ("left hip", "right hip"),
        # Lower body connections
        ("left hip", "left knee"),
        ("right hip", "right knee"),
        ("left knee", "left ankle"),
        ("right knee", "right ankle"),
    ]

    # Hand skeleton connections
    hand_skeleton_connections = [
        # Thumb connections
        ("wrist", "thumb root"),
        ("thumb root", "thumb's third knuckle"),
        ("thumb's third knuckle", "thumb's second knuckle"),
        ("thumb's second knuckle", "thumb's first knuckle"),
        # Forefinger connections
        ("wrist", "forefinger's root"),
        ("forefinger's root", "forefinger's third knuckle"),
        ("forefinger's third knuckle", "forefinger's second knuckle"),
        ("forefinger's second knuckle", "forefinger's first knuckle"),
        # Middle finger connections
        ("wrist", "middle finger's root"),
        ("middle finger's root", "middle finger's third knuckle"),
        ("middle finger's third knuckle", "middle finger's second knuckle"),
        ("middle finger's second knuckle", "middle finger's first knuckle"),
        # Ring finger connections
        ("wrist", "ring finger's root"),
        ("ring finger's root", "ring finger's third knuckle"),
        ("ring finger's third knuckle", "ring finger's second knuckle"),
        ("ring finger's second knuckle", "ring finger's first knuckle"),
        # Pinky finger connections
        ("wrist", "pinky finger's root"),
        ("pinky finger's root", "pinky finger's third knuckle"),
        ("pinky finger's third knuckle", "pinky finger's second knuckle"),
        ("pinky finger's second knuckle", "pinky finger's first knuckle"),
    ]

    # Animal skeleton connections
    animal_skeleton_connections = [
        # Head connections
        ("left eye", "right eye"),
        ("left eye", "nose"),
        ("right eye", "nose"),
        ("nose", "neck"),
        # Body connections
        ("neck", "left shoulder"),
        ("neck", "right shoulder"),
        ("left shoulder", "left elbow"),
        ("right shoulder", "right elbow"),
        ("left elbow", "left front paw"),
        ("right elbow", "right front paw"),
        # Hip connections
        ("neck", "left hip"),
        ("neck", "right hip"),
        ("left hip", "left knee"),
        ("right hip", "right knee"),
        ("left knee", "left back paw"),
        ("right knee", "right back paw"),
        # Tail connection
        ("neck", "root of tail"),
    ]

    # Determine skeleton type based on keypoints
    if "wrist" in keypoints:
        connections = hand_skeleton_connections
    elif "left shoulder" in keypoints and "left hip" in keypoints:
        connections = skeleton_connections
    else:
        connections = animal_skeleton_connections

    # Calculate dynamic keypoint radius based on bbox size
    if len(bbox) == 4:
        x0, y0, x1, y1 = bbox
        bbox_area = (x1 - x0) * (y1 - y0)
        # Dynamic radius based on bbox size, with max 5 pixels
        dynamic_radius = max(2, min(5, int((bbox_area / 10000) ** 0.5 * 4)))
    else:
        dynamic_radius = max(4, draw_width // 2)

    # Draw skeleton connections with light blue color
    skeleton_color = (173, 216, 230)  # Light blue color (RGB)
    for connection in connections:
        kp1_name, kp2_name = connection
        if (
            kp1_name in keypoints
            and kp2_name in keypoints
            and keypoints[kp1_name] != "unvisible"
            and keypoints[kp2_name] != "unvisible"
        ):
            kp1_coords = keypoints[kp1_name]
            kp2_coords = keypoints[kp2_name]

            if (
                isinstance(kp1_coords, list)
                and len(kp1_coords) == 2
                and isinstance(kp2_coords, list)
                and len(kp2_coords) == 2
            ):
                x1, y1 = int(kp1_coords[0]), int(kp1_coords[1])
                x2, y2 = int(kp2_coords[0]), int(kp2_coords[1])

                # Draw line between keypoints
                draw.line([(x1, y1), (x2, y2)], fill=skeleton_color, width=4)

    # Draw keypoints using blue-white scheme
    for kp_name, kp_coords in keypoints.items():
        if (
            kp_coords != "unvisible"
            and isinstance(kp_coords, list)
            and len(kp_coords) == 2
        ):
            x, y = int(kp_coords[0]), int(kp_coords[1])

            # Use blue color for all keypoints (similar to vis_converted.py)
            kp_color = (51, 153, 255)  # Blue color (RGB)

            # Draw point as a circle with white outline (like vis_converted.py)
            draw.ellipse(
                [
                    x - dynamic_radius,
                    y - dynamic_radius,
                    x + dynamic_radius,
                    y + dynamic_radius,
                ],
                fill=kp_color,
                outline="white",
                width=3,
            )


def format_predictions_for_display(predictions: Dict[str, List[Dict]]) -> str:
    """Format predictions for text display"""
    if not predictions:
        return "No predictions found."

    lines = []
    for category, annotations in predictions.items():
        lines.append(f"\n{category.upper()}:")
        for i, annotation in enumerate(annotations):
            ann_type = annotation.get("type", "unknown")
            coords = annotation.get("coords", [])

            if ann_type == "box" and len(coords) == 4:
                x0, y0, x1, y1 = coords
                lines.append(f"  Box {i+1}: ({x0:.1f}, {y0:.1f}, {x1:.1f}, {y1:.1f})")
            elif ann_type == "point" and len(coords) == 2:
                x, y = coords
                lines.append(f"  Point {i+1}: ({x:.1f}, {y:.1f})")
            elif ann_type == "polygon":
                lines.append(f"  Polygon {i+1}: {len(coords)} points")
            elif ann_type == "keypoint":
                bbox = annotation.get("bbox", [])
                keypoints = annotation.get("keypoints", {})
                visible_kps = sum(1 for kp in keypoints.values() if kp != "unvisible")
                lines.append(
                    f"  Instance {i+1}: {visible_kps}/{len(keypoints)} keypoints visible"
                )

    return "\n".join(lines)