File size: 2,075 Bytes
edae372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Resolve COCO JSON paths under ``data/scenes/<scene>/`` after renames:



- ``_annotations_fixed.coco.json`` -> ``_annotations_original.coco.json``

- ``_annotations_supplementary.coco.json`` -> ``_annotations_extended.coco.json``



``extended`` adds annotations on the same images as ``original``; both may be present.

"""
from __future__ import annotations

from pathlib import Path
from typing import List, Optional

# Single canonical file for frame list / image dimensions (first match wins).
RESOLVE_ORDER: tuple[str, ...] = (
    "_annotations_original.coco.json",
    "_annotations_extended.coco.json",
    "_annotations_fixed.coco.json",
    "_annotations.coco.json",
)

# All COCO files to rasterize for per-instance masks (original then extended; skip legacy dup).
MASK_GENERATION_ORDER: tuple[str, ...] = (
    "_annotations_original.coco.json",
    "_annotations_extended.coco.json",
    "_annotations_fixed.coco.json",
)


def resolve_scene_coco_annotation(scene_dir: Path) -> Optional[Path]:
    """One annotation file for frame_id / H,W lookup."""
    for name in RESOLVE_ORDER:
        p = scene_dir / name
        if p.is_file():
            return p
    return None


def iter_scene_coco_for_masks(scene_dir: Path) -> List[Path]:
    """

    COCO files to generate instance_masks from. Uses ``_annotations.coco.json`` only if

    no renamed file exists (older scenes).

    """
    out: List[Path] = []
    for name in MASK_GENERATION_ORDER:
        p = scene_dir / name
        if p.is_file():
            out.append(p)
    if not out:
        p = scene_dir / "_annotations.coco.json"
        if p.is_file():
            out.append(p)
    return out


def open_coco_json(path: Path):
    import json

    for enc in ("utf-8-sig", "utf-8"):
        try:
            with path.open("r", encoding=enc) as f:
                return json.load(f)
        except UnicodeDecodeError:
            continue
    with path.open("r", encoding="utf-8", errors="replace") as f:
        return json.load(f)