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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
#!/usr/bin/env python3
"""Validate LEVIR-Ship, create leakage-safe splits, and export COCO JSON.

Expected input layout::

    DATA_ROOT/
    ├── All Images/       # PNG images
    └── All Annotations/  # YOLO TXT labels with matching basenames

The script does not copy images. COCO ``file_name`` values remain basenames, so
MMDetection should point ``data_prefix.img`` at ``DATA_ROOT/All Images``.

Typical live-marimo usage after downloading the dataset into ``/marimo``::

    cd /marimo
    python preprocess_data.py --data-root . --verify-only
    python preprocess_data.py --data-root .
"""

from __future__ import annotations

import argparse
import json
import math
import random
import re
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable

from PIL import Image


SPLIT_NAMES = ("train", "val", "test")
SCENE_RE = re.compile(r"^(.*)_(-?\d+)_(-?\d+)$")
PRODUCT_VARIANT_RE = re.compile(r"-\d+$")


@dataclass(frozen=True)
class Sample:
    image_path: Path
    annotation_path: Path
    scene: str
    product: str
    width: int
    height: int
    boxes: tuple[tuple[float, float, float, float], ...]

    @property
    def is_positive(self) -> bool:
        return bool(self.boxes)


@dataclass(frozen=True)
class GroupStats:
    images: int
    positives: int
    boxes: int

    def __add__(self, other: "GroupStats") -> "GroupStats":
        return GroupStats(
            images=self.images + other.images,
            positives=self.positives + other.positives,
            boxes=self.boxes + other.boxes,
        )


ZERO_STATS = GroupStats(images=0, positives=0, boxes=0)


def resolve_path(value: str | Path) -> Path:
    """Resolve CLI paths relative to the current working directory."""
    path = Path(value).expanduser()
    return path.resolve() if path.is_absolute() else (Path.cwd() / path).resolve()


def parse_scene_and_product(image_path: Path) -> tuple[str, str]:
    """Return the tile's scene variant and core source-product identifier."""
    match = SCENE_RE.match(image_path.stem)
    if not match:
        raise ValueError(
            "Cannot extract source scene and tile coordinates from "
            f"{image_path.name}"
        )
    scene = match.group(1)
    product = PRODUCT_VARIANT_RE.sub("", scene)
    return scene, product


def parse_yolo_boxes(
    annotation_path: Path, width: int, height: int
) -> tuple[tuple[float, float, float, float], ...]:
    """Parse one single-class YOLO file into float COCO ``xywh`` boxes."""
    boxes: list[tuple[float, float, float, float]] = []
    seen: set[tuple[float, float, float, float, float]] = set()

    for line_number, raw_line in enumerate(
        annotation_path.read_text(encoding="utf-8").splitlines(), 1
    ):
        line = raw_line.strip()
        if not line:
            continue
        parts = line.split()
        if len(parts) != 5:
            raise ValueError(
                f"{annotation_path}:{line_number}: expected 5 YOLO values, "
                f"got {len(parts)}"
            )
        try:
            class_id, cx, cy, box_width, box_height = map(float, parts)
        except ValueError as exc:
            raise ValueError(
                f"{annotation_path}:{line_number}: non-numeric YOLO value"
            ) from exc

        values = (class_id, cx, cy, box_width, box_height)
        if not all(math.isfinite(value) for value in values):
            raise ValueError(
                f"{annotation_path}:{line_number}: non-finite YOLO value"
            )
        if class_id != 0:
            raise ValueError(
                f"{annotation_path}:{line_number}: expected class 0, "
                f"got {class_id:g}"
            )
        if not (0.0 <= cx <= 1.0 and 0.0 <= cy <= 1.0):
            raise ValueError(
                f"{annotation_path}:{line_number}: center is outside [0, 1]"
            )
        if box_width <= 0.0 or box_height <= 0.0:
            raise ValueError(
                f"{annotation_path}:{line_number}: width and height must be positive"
            )

        x1_raw = (cx - box_width / 2.0) * width
        y1_raw = (cy - box_height / 2.0) * height
        x2_raw = (cx + box_width / 2.0) * width
        y2_raw = (cy + box_height / 2.0) * height
        tolerance = 1e-6
        if (
            x1_raw < -tolerance
            or y1_raw < -tolerance
            or x2_raw > width + tolerance
            or y2_raw > height + tolerance
        ):
            raise ValueError(
                f"{annotation_path}:{line_number}: bounding box exceeds image bounds"
            )

        x1 = max(0.0, x1_raw)
        y1 = max(0.0, y1_raw)
        x2 = min(float(width), x2_raw)
        y2 = min(float(height), y2_raw)
        if x2 <= x1 or y2 <= y1:
            raise ValueError(
                f"{annotation_path}:{line_number}: invalid bounding box"
            )
        if values in seen:
            raise ValueError(
                f"{annotation_path}:{line_number}: duplicate annotation line"
            )
        seen.add(values)
        boxes.append((x1, y1, x2 - x1, y2 - y1))

    return tuple(boxes)


def discover_samples(
    data_root: Path,
    image_dir_name: str = "All Images",
    annotation_dir_name: str = "All Annotations",
) -> list[Sample]:
    """Validate all image-label pairs and return parsed samples."""
    image_dir = data_root / image_dir_name
    annotation_dir = data_root / annotation_dir_name
    if not image_dir.is_dir() or not annotation_dir.is_dir():
        raise FileNotFoundError(
            f"Expected '{image_dir_name}' and '{annotation_dir_name}' under "
            f"{data_root}"
        )

    image_paths = sorted(image_dir.glob("*.png"), key=lambda path: path.name)
    annotation_paths = sorted(
        annotation_dir.glob("*.txt"), key=lambda path: path.name
    )
    if not image_paths:
        raise ValueError(f"No PNG images found in {image_dir}")

    image_stems = {path.stem for path in image_paths}
    annotation_stems = {path.stem for path in annotation_paths}
    missing_annotations = sorted(image_stems - annotation_stems)
    orphan_annotations = sorted(annotation_stems - image_stems)
    if missing_annotations or orphan_annotations:
        details = []
        if missing_annotations:
            details.append(
                f"{len(missing_annotations)} images without labels "
                f"(first: {missing_annotations[0]}.png)"
            )
        if orphan_annotations:
            details.append(
                f"{len(orphan_annotations)} labels without images "
                f"(first: {orphan_annotations[0]}.txt)"
            )
        raise ValueError("; ".join(details))

    samples: list[Sample] = []
    for image_path in image_paths:
        annotation_path = annotation_dir / f"{image_path.stem}.txt"
        scene, product = parse_scene_and_product(image_path)
        try:
            with Image.open(image_path) as image:
                width, height = image.size
                mode = image.mode
                image.verify()
        except Exception as exc:
            raise ValueError(f"Cannot verify image {image_path}") from exc
        if mode != "RGB":
            raise ValueError(f"Expected RGB image, got {mode} for {image_path}")
        boxes = parse_yolo_boxes(annotation_path, width, height)
        samples.append(
            Sample(
                image_path=image_path,
                annotation_path=annotation_path,
                scene=scene,
                product=product,
                width=width,
                height=height,
                boxes=boxes,
            )
        )
    return samples


def sample_stats(samples: Iterable[Sample]) -> GroupStats:
    sample_list = list(samples)
    return GroupStats(
        images=len(sample_list),
        positives=sum(sample.is_positive for sample in sample_list),
        boxes=sum(len(sample.boxes) for sample in sample_list),
    )


def validate_ratios(ratios: dict[str, float]) -> None:
    if set(ratios) != set(SPLIT_NAMES):
        raise ValueError(f"Ratios must define exactly: {', '.join(SPLIT_NAMES)}")
    if any(value <= 0.0 for value in ratios.values()):
        raise ValueError("All split ratios must be positive")
    if not math.isclose(sum(ratios.values()), 1.0, rel_tol=0.0, abs_tol=1e-9):
        raise ValueError(f"Split ratios must sum to 1, got {sum(ratios.values())}")


def split_samples(
    samples: list[Sample],
    *,
    ratios: dict[str, float],
    seed: int,
    group_level: str = "product",
) -> dict[str, list[Sample]]:
    """Greedily balance images, positives, and boxes without group leakage."""
    validate_ratios(ratios)
    if group_level not in {"product", "scene"}:
        raise ValueError("group_level must be 'product' or 'scene'")

    groups: dict[str, list[Sample]] = defaultdict(list)
    for sample in samples:
        key = sample.product if group_level == "product" else sample.scene
        groups[key].append(sample)
    if len(groups) < len(SPLIT_NAMES):
        raise ValueError(
            f"Need at least {len(SPLIT_NAMES)} groups, found {len(groups)}"
        )

    total = sample_stats(samples)
    targets = {
        split: GroupStats(
            images=max(1.0, total.images * ratios[split]),
            positives=max(1.0, total.positives * ratios[split]),
            boxes=max(1.0, total.boxes * ratios[split]),
        )
        for split in SPLIT_NAMES
    }
    group_items = [(name, group, sample_stats(group)) for name, group in groups.items()]
    rng = random.Random(seed)
    rng.shuffle(group_items)
    group_items.sort(
        key=lambda item: (
            item[2].images / max(total.images, 1),
            item[2].positives / max(total.positives, 1),
            item[2].boxes / max(total.boxes, 1),
        ),
        reverse=True,
    )

    counts = {split: ZERO_STATS for split in SPLIT_NAMES}
    raw_capacities = {
        split: len(groups) * ratios[split] for split in SPLIT_NAMES
    }
    group_capacities = {
        split: math.floor(raw_capacities[split]) for split in SPLIT_NAMES
    }
    unassigned_slots = len(groups) - sum(group_capacities.values())
    capacity_order = sorted(
        SPLIT_NAMES,
        key=lambda split: (
            raw_capacities[split] - group_capacities[split],
            -SPLIT_NAMES.index(split),
        ),
        reverse=True,
    )
    for split in capacity_order[:unassigned_slots]:
        group_capacities[split] += 1
    assigned_group_counts = {split: 0 for split in SPLIT_NAMES}
    assignments: dict[str, str] = {}

    def objective(candidate: str, group_stats: GroupStats) -> float:
        projected = dict(counts)
        projected[candidate] = projected[candidate] + group_stats
        score = 0.0
        for split in SPLIT_NAMES:
            for metric, weight in (
                ("images", 1.0),
                ("positives", 1.0),
                ("boxes", 0.5),
            ):
                target = float(getattr(targets[split], metric))
                delta = (getattr(projected[split], metric) - target) / target
                score += weight * delta * delta
        return score

    for group_name, _, group_stats in group_items:
        eligible_splits = [
            split
            for split in SPLIT_NAMES
            if assigned_group_counts[split] < group_capacities[split]
        ]
        split = min(
            eligible_splits,
            key=lambda name: (objective(name, group_stats), SPLIT_NAMES.index(name)),
        )
        assignments[group_name] = split
        counts[split] = counts[split] + group_stats
        assigned_group_counts[split] += 1

    output = {split: [] for split in SPLIT_NAMES}
    for group_name, group, _ in group_items:
        output[assignments[group_name]].extend(group)
    for split in SPLIT_NAMES:
        output[split].sort(key=lambda sample: sample.image_path.name)
        if not output[split]:
            raise AssertionError(f"Split '{split}' is empty")

    assert_no_group_leakage(output, group_level)
    return output


def assert_no_group_leakage(
    split_samples: dict[str, list[Sample]], group_level: str
) -> None:
    group_sets = {}
    for split, samples in split_samples.items():
        group_sets[split] = {
            sample.product if group_level == "product" else sample.scene
            for sample in samples
        }
    for index, left in enumerate(SPLIT_NAMES):
        for right in SPLIT_NAMES[index + 1 :]:
            overlap = group_sets[left] & group_sets[right]
            if overlap:
                example = sorted(overlap)[0]
                raise AssertionError(
                    f"{group_level} leakage between {left} and {right}: {example}"
                )


def build_coco_payload(
    samples: list[Sample], *, seed: int, group_level: str
) -> dict[str, object]:
    images: list[dict[str, object]] = []
    annotations: list[dict[str, object]] = []
    annotation_id = 1
    for image_id, sample in enumerate(samples, 1):
        images.append(
            {
                "id": image_id,
                "file_name": sample.image_path.name,
                "width": sample.width,
                "height": sample.height,
            }
        )
        for x, y, width, height in sample.boxes:
            annotations.append(
                {
                    "id": annotation_id,
                    "image_id": image_id,
                    "category_id": 1,
                    "bbox": [x, y, width, height],
                    "area": width * height,
                    "iscrowd": 0,
                    "segmentation": [],
                }
            )
            annotation_id += 1
    return {
        "info": {
            "description": "LEVIR-Ship converted from YOLO to COCO",
            "version": "1.0",
            "source_format": "YOLO normalized xywh",
            "split_seed": seed,
            "split_group": group_level,
        },
        "licenses": [],
        "images": images,
        "annotations": annotations,
        "categories": [{"id": 1, "name": "ship", "supercategory": "ship"}],
    }


def atomic_write_json(path: Path, payload: object) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(
        json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    temporary.replace(path)


def split_summary(samples: list[Sample]) -> dict[str, object]:
    stats = sample_stats(samples)
    return {
        "images": stats.images,
        "scenes": len({sample.scene for sample in samples}),
        "products": len({sample.product for sample in samples}),
        "positive_images": stats.positives,
        "negative_images": stats.images - stats.positives,
        "boxes": stats.boxes,
        "files": [sample.image_path.name for sample in samples],
    }


def preprocess(args: argparse.Namespace) -> tuple[Path, Path]:
    data_root = resolve_path(args.data_root)
    dataset_out = resolve_path(args.dataset_out)
    ratios = {
        "train": args.train_ratio,
        "val": args.val_ratio,
        "test": args.test_ratio,
    }
    samples = discover_samples(
        data_root,
        image_dir_name=args.image_dir,
        annotation_dir_name=args.annotation_dir,
    )
    split_data = split_samples(
        samples,
        ratios=ratios,
        seed=args.seed,
        group_level=args.group_level,
    )
    if args.limit > 0:
        split_data = {
            split: split_samples_for_name[: args.limit]
            for split, split_samples_for_name in split_data.items()
        }

    summary = {
        "version": 1,
        "source": {
            "data_root": str(data_root),
            "image_dir": args.image_dir,
            "annotation_dir": args.annotation_dir,
        },
        "seed": args.seed,
        "group_level": args.group_level,
        "ratios": ratios,
        "class_map": {"yolo_0": "ship", "coco_1": "ship"},
        "splits": {
            split: split_summary(split_data[split]) for split in SPLIT_NAMES
        },
    }

    total_stats = sample_stats(samples)
    print(
        f"Validated {total_stats.images} images, {total_stats.positives} positives, "
        f"{total_stats.boxes} boxes"
    )
    for split in SPLIT_NAMES:
        stats = summary["splits"][split]
        print(
            f"{split}: images={stats['images']} scenes={stats['scenes']} "
            f"products={stats['products']} positives={stats['positive_images']} "
            f"negatives={stats['negative_images']} boxes={stats['boxes']}"
        )

    if args.verify_only:
        print("Verification complete; no files written")
        return dataset_out, data_root / args.image_dir

    annotation_out = dataset_out / "annotations"
    for split in SPLIT_NAMES:
        atomic_write_json(
            annotation_out / f"{split}.json",
            build_coco_payload(
                split_data[split], seed=args.seed, group_level=args.group_level
            ),
        )
    atomic_write_json(dataset_out / "split_manifest.json", summary)
    print(f"COCO annotations: {annotation_out}")
    print(f"Split manifest: {dataset_out / 'split_manifest.json'}")
    print(f"Image directory (not copied): {data_root / args.image_dir}")
    return dataset_out, data_root / args.image_dir


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--data-root",
        default=".",
        help="Directory containing 'All Images' and 'All Annotations'.",
    )
    parser.add_argument(
        "--dataset-out",
        default="mmdetection/data/levir_ship_coco",
        help="Output directory for COCO annotations and the split manifest.",
    )
    parser.add_argument("--image-dir", default="All Images")
    parser.add_argument("--annotation-dir", default="All Annotations")
    parser.add_argument(
        "--group-level",
        choices=("product", "scene"),
        default="product",
        help=(
            "Leakage boundary. 'product' also keeps -1/-2/-3 scene variants "
            "together and is the research-safe default."
        ),
    )
    parser.add_argument("--train-ratio", type=float, default=0.70)
    parser.add_argument("--val-ratio", type=float, default=0.15)
    parser.add_argument("--test-ratio", type=float, default=0.15)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument(
        "--limit",
        type=int,
        default=0,
        help="Smoke-test cap per split after splitting; 0 keeps all images.",
    )
    parser.add_argument(
        "--verify-only",
        action="store_true",
        help="Validate and calculate the split without writing output files.",
    )
    args = parser.parse_args()
    if args.limit < 0:
        parser.error("--limit must be >= 0")
    return args


def main() -> None:
    preprocess(parse_args())


if __name__ == "__main__":
    main()