lookonce 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lookonce/__init__.py ADDED
@@ -0,0 +1,73 @@
1
+ """lookonce: 사전학습 YOLO 모델로 객체를 탐지하고, 내 데이터로 미세조정한다.
2
+
3
+ from lookonce import Detector
4
+
5
+ detector = Detector() # 기본 사전학습 모델
6
+ result = detector.detect("street.jpg")
7
+ print(result.counts()) # {'person': 4, 'bus': 1}
8
+ result.save("street_boxes.jpg")
9
+
10
+ 미세조정:
11
+
12
+ from lookonce import Dataset, finetune
13
+
14
+ ds = Dataset("helmets")
15
+ ds.add_image("site1.jpg", boxes=[("helmet", 120, 40, 260, 190)])
16
+ info = finetune(ds, epochs=30, name="helmet-v1")
17
+ Detector("helmet-v1").detect("site2.jpg")
18
+
19
+ 웹 UI:
20
+
21
+ import lookonce
22
+ lookonce.launch_ui() # 또는 터미널에서: lookonce ui
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from typing import Any
28
+
29
+ from .capture import CaptureSession
30
+ from .dataset import Box, Dataset, ImageItem, delete_dataset, list_datasets
31
+ from .detector import Detector, detect, load_image
32
+ from .paths import home, set_home
33
+ from .registry import DEFAULT_MODEL, PRETRAINED, ModelInfo, delete_model, list_models
34
+ from .registry import download as download_model
35
+ from .results import Detection, DetectionResult
36
+ from .training import TrainingCancelled, TrainProgress, finetune
37
+
38
+ # 버전은 여기 한 곳에서만 정한다 (pyproject.toml이 이 값을 읽는다). 바꿀 때는 CHANGELOG.md에도 적는다.
39
+ # 주.부.수 형식: 호환이 깨지는 변경은 주, 기능 추가는 부, 오류 수정은 수를 올린다.
40
+ __version__ = "1.0.0"
41
+
42
+ __all__ = [
43
+ "Box",
44
+ "CaptureSession",
45
+ "DEFAULT_MODEL",
46
+ "Dataset",
47
+ "Detection",
48
+ "DetectionResult",
49
+ "Detector",
50
+ "ImageItem",
51
+ "ModelInfo",
52
+ "PRETRAINED",
53
+ "TrainProgress",
54
+ "TrainingCancelled",
55
+ "delete_dataset",
56
+ "delete_model",
57
+ "detect",
58
+ "download_model",
59
+ "finetune",
60
+ "home",
61
+ "launch_ui",
62
+ "list_datasets",
63
+ "list_models",
64
+ "load_image",
65
+ "set_home",
66
+ ]
67
+
68
+
69
+ def launch_ui(**options: Any) -> None:
70
+ """웹 UI를 띄운다. `pip install "lookonce[ui]"`가 필요하다."""
71
+ from .ui import launch
72
+
73
+ launch(**options)
lookonce/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
lookonce/capture.py ADDED
@@ -0,0 +1,118 @@
1
+ """탐지 결과 기록: 상자를 그린 이미지와 detections.csv를 한 폴더에 모은다.
2
+
3
+ >>> from lookonce import CaptureSession, Detector
4
+ >>> session = CaptureSession("captures", kind="webcam")
5
+ >>> for result in Detector().stream(0):
6
+ ... session.add(result)
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import csv
12
+ import threading
13
+ import time
14
+ from pathlib import Path
15
+ from typing import Any, Dict, Optional, Union
16
+
17
+ from PIL import Image
18
+
19
+ from .paths import safe_name
20
+ from .results import DetectionResult
21
+
22
+ CSV_NAME = "detections.csv"
23
+ CSV_COLUMNS = [
24
+ "file", # 상자를 그린 이미지 파일 이름
25
+ "saved_at", # 저장한 시각
26
+ "video_time", # 영상 파일에서의 위치(초). 웹캠이면 비어 있다
27
+ "model",
28
+ "conf_threshold", # 탐지에 쓴 신뢰도 기준
29
+ "objects", # 이 이미지에서 찾은 물체 수
30
+ "label",
31
+ "confidence",
32
+ "x1", "y1", "x2", "y2", # 저장한 이미지의 픽셀 좌표
33
+ ]
34
+
35
+ # 기록 종류 -> 폴더 이름 끝에 붙는 접미사
36
+ KIND_SUFFIX = {"webcam": "webcam", "image": "image", "video": "movies"}
37
+
38
+
39
+ class CaptureSession:
40
+ """기록 한 번(웹캠을 한 번 켠 동안, 또는 이미지나 영상 여러 개)에 해당하는 폴더.
41
+
42
+ 폴더 이름은 종류를 나타내는 접미사로 끝난다.
43
+
44
+ 날짜-시각-webcam 웹캠을 한 번 켠 동안
45
+ 날짜-시각-image 이미지 여러 장
46
+ 날짜-시각-movies 영상 여러 개
47
+
48
+ title을 주면 접미사 앞에 들어간다(날짜-시각-제목-movies). 보통은 주지 않고,
49
+ 어느 파일의 결과인지는 add()의 label로 파일 이름에 남긴다: 000001-여행.jpg
50
+
51
+ 안에는 000001.jpg, 000002.jpg … 와 detections.csv가 생긴다.
52
+ detections.csv는 물체 하나에 한 줄이며, 물체가 없는 이미지도 objects=0으로 한 줄 남는다.
53
+ """
54
+
55
+ def __init__(self, root: Union[str, Path], *, kind: str = "webcam", title: Optional[str] = None) -> None:
56
+ root = Path(root).expanduser()
57
+ stamp = time.strftime("%Y%m%d-%H%M%S")
58
+ try:
59
+ middle = f"-{safe_name(title)}" if title else ""
60
+ except ValueError:
61
+ middle = "" # 이름으로 쓸 글자가 없으면 뺀다
62
+ suffix = KIND_SUFFIX.get(kind) or safe_name(kind)
63
+ path, n = root / f"{stamp}{middle}-{suffix}", 1
64
+ while path.exists(): # 같은 초에 같은 이름이 또 생기면 번호를 붙인다. 접미사는 맨 끝에 둔다
65
+ n += 1
66
+ path = root / f"{stamp}{middle}-{n}-{suffix}"
67
+ path.mkdir(parents=True)
68
+ self.dir = path
69
+ self.id = path.name
70
+ self.kind = kind
71
+ self.count = 0
72
+ self._lock = threading.Lock()
73
+ # utf-8-sig: 엑셀에서 한글 라벨이 깨지지 않게 한다
74
+ with (self.dir / CSV_NAME).open("w", newline="", encoding="utf-8-sig") as f:
75
+ csv.writer(f).writerow(CSV_COLUMNS)
76
+
77
+ def add(
78
+ self,
79
+ result: DetectionResult,
80
+ *,
81
+ video_time: Optional[float] = None,
82
+ conf: Optional[float] = None,
83
+ quality: int = 90,
84
+ label: Optional[str] = None,
85
+ ) -> Path:
86
+ """탐지 결과 하나를 이미지와 CSV 줄로 저장하고, 이미지 경로를 돌려준다.
87
+
88
+ label(원본 파일 이름 등)을 주면 저장하는 파일 이름 뒤에 붙인다: 000001-bus.jpg
89
+ """
90
+ suffix = ""
91
+ if label:
92
+ try:
93
+ suffix = "-" + safe_name(Path(str(label).replace("\\", "/")).stem)[:40]
94
+ except ValueError:
95
+ suffix = "" # 이름으로 쓸 글자가 없으면 번호만 쓴다
96
+ with self._lock:
97
+ self.count += 1
98
+ name = f"{self.count:06d}{suffix}.jpg"
99
+ path = self.dir / name
100
+ Image.fromarray(result.plot()[:, :, ::-1]).save(path, quality=quality)
101
+ common = [
102
+ name,
103
+ time.strftime("%Y-%m-%d %H:%M:%S"),
104
+ "" if video_time is None else f"{video_time:.2f}",
105
+ result.model,
106
+ "" if conf is None else f"{conf:.2f}",
107
+ len(result),
108
+ ]
109
+ rows = [
110
+ common + [d.label, f"{d.confidence:.3f}", *(round(v) for v in d.box)]
111
+ for d in result
112
+ ] or [common + ["", "", "", "", "", ""]]
113
+ with (self.dir / CSV_NAME).open("a", newline="", encoding="utf-8-sig") as f:
114
+ csv.writer(f).writerows(rows)
115
+ return path
116
+
117
+ def to_dict(self) -> Dict[str, Any]:
118
+ return {"id": self.id, "path": str(self.dir), "count": self.count, "kind": self.kind}
lookonce/cli.py ADDED
@@ -0,0 +1,125 @@
1
+ """명령줄: lookonce ui | detect | models"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from typing import List, Optional
8
+
9
+ from . import registry
10
+
11
+
12
+ def _parser() -> argparse.ArgumentParser:
13
+ from . import __version__
14
+
15
+ parser = argparse.ArgumentParser(prog="lookonce", description="YOLO 객체 탐지와 미세조정")
16
+ parser.add_argument("--version", action="version", version=f"lookonce {__version__}")
17
+ parser.add_argument(
18
+ "--home",
19
+ default=None,
20
+ help="모델·데이터셋을 보관할 폴더 (기본: 환경변수 LOOKONCE_HOME, 없으면 프로젝트 폴더, 일반 설치면 ~/.lookonce)",
21
+ )
22
+ sub = parser.add_subparsers(dest="command", required=True)
23
+
24
+ ui = sub.add_parser("ui", help="웹 UI를 띄운다")
25
+ ui.add_argument("--host", default="127.0.0.1")
26
+ ui.add_argument("--port", type=int, default=7860)
27
+ ui.add_argument("--model", default=None, help="처음에 쓸 모델")
28
+ ui.add_argument("--no-browser", action="store_true", help="브라우저를 자동으로 열지 않는다")
29
+ ui.add_argument(
30
+ "--captures",
31
+ default=None,
32
+ help="녹화한 결과(이미지, detections.csv)를 저장할 폴더 (기본: 실행한 폴더의 captures)",
33
+ )
34
+
35
+ det = sub.add_parser("detect", help="이미지에서 물체를 찾는다")
36
+ det.add_argument("source", help="이미지 파일 경로")
37
+ det.add_argument("--model", default=registry.DEFAULT_MODEL)
38
+ det.add_argument("--conf", type=float, default=0.25, help="신뢰도 기준 (기본 0.25)")
39
+ det.add_argument("--save", default=None, help="상자를 그린 이미지를 저장할 경로")
40
+ det.add_argument("--json", action="store_true", help="결과를 JSON으로 출력한다")
41
+
42
+ sub.add_parser("models", help="쓸 수 있는 모델 목록")
43
+
44
+ down = sub.add_parser("download", help="사전학습 모델을 미리 내려받는다 (처음 쓸 때도 자동으로 받는다)")
45
+ down.add_argument(
46
+ "models",
47
+ nargs="*",
48
+ default=[registry.DEFAULT_MODEL],
49
+ help=f"내려받을 모델 이름들 (기본: {registry.DEFAULT_MODEL})",
50
+ )
51
+ return parser
52
+
53
+
54
+ def main(argv: Optional[List[str]] = None) -> int:
55
+ for stream in (sys.stdout, sys.stderr):
56
+ try:
57
+ stream.reconfigure(encoding="utf-8") # type: ignore[union-attr]
58
+ except (AttributeError, ValueError):
59
+ pass
60
+ args = _parser().parse_args(argv)
61
+ if args.home:
62
+ from .paths import set_home
63
+
64
+ set_home(args.home)
65
+
66
+ if args.command == "ui":
67
+ from .ui import launch
68
+
69
+ launch(
70
+ host=args.host,
71
+ port=args.port,
72
+ model=args.model,
73
+ open_browser=not args.no_browser,
74
+ captures=args.captures,
75
+ )
76
+ return 0
77
+
78
+ if args.command == "detect":
79
+ from .detector import Detector
80
+
81
+ result = Detector(args.model, conf=args.conf).detect(args.source)
82
+ if args.json:
83
+ print(result.to_json(indent=2))
84
+ else:
85
+ for d in result:
86
+ x1, y1, x2, y2 = (round(v) for v in d.box)
87
+ print(f"{d.label:<16} {d.confidence:.2f} ({x1}, {y1}) - ({x2}, {y2})")
88
+ print(f"물체 {len(result)}개 · {result.speed_ms:.0f} ms")
89
+ if args.save:
90
+ print(f"저장: {result.save(args.save)}")
91
+ return 0
92
+
93
+ if args.command == "models":
94
+ for info in registry.list_models():
95
+ size = f"{info.size_mb:.1f} MB" if info.size_mb is not None else "-"
96
+ if info.kind == "pretrained":
97
+ status = "받음" if info.downloaded else "처음 쓸 때 내려받음"
98
+ print(f"{info.name:<20} {size:>9} 사전학습 {info.family} · {info.description} ({status})")
99
+ else:
100
+ classes = ", ".join(info.classes or [])
101
+ print(f"{info.name:<20} {size:>9} 미세조정 {info.base} 기반 · 클래스: {classes}")
102
+ return 0
103
+
104
+ if args.command == "download":
105
+ failed = 0
106
+ for name in args.models:
107
+ try:
108
+ info = registry.resolve(name)
109
+ if info.downloaded:
110
+ print(f"{info.name}: 이미 있음 ({info.path})")
111
+ continue
112
+ size = f"약 {info.size_mb:.1f} MB" if info.size_mb is not None else "크기 모름"
113
+ print(f"{info.name}: 내려받는 중 ({size})")
114
+ registry.download(name)
115
+ print(f"{info.name}: 받음 ({info.path})")
116
+ except (OSError, FileNotFoundError) as error:
117
+ failed += 1
118
+ print(f"{name}: 실패 - {error}")
119
+ return 1 if failed else 0
120
+
121
+ return 1
122
+
123
+
124
+ if __name__ == "__main__":
125
+ raise SystemExit(main())
lookonce/dataset.py ADDED
@@ -0,0 +1,360 @@
1
+ """Dataset: 미세조정에 쓸 이미지와 상자 라벨을 모아 둔다."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import threading
9
+ import uuid
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union
13
+
14
+ from PIL import Image, ImageOps
15
+
16
+ from .paths import home, safe_name
17
+
18
+ BoxInput = Union[Dict[str, Any], Sequence[Any]]
19
+
20
+ MIN_BOX_PX = 2.0
21
+ VAL_SPLIT_MIN_IMAGES = 10 # 이보다 적으면 검증에도 학습 이미지를 그대로 쓴다
22
+ MIN_TRAIN_SAMPLES = 32 # epoch마다 학습에 쓰는 최소 이미지 수 (모자라면 반복)
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Box:
27
+ """라벨 상자 하나. 좌표는 이미지 픽셀 (x1, y1, x2, y2)."""
28
+
29
+ label: str
30
+ x1: float
31
+ y1: float
32
+ x2: float
33
+ y2: float
34
+
35
+ def to_dict(self) -> Dict[str, Any]:
36
+ return {"label": self.label, "box": [self.x1, self.y1, self.x2, self.y2]}
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class ImageItem:
41
+ id: str
42
+ path: Path
43
+ width: int
44
+ height: int
45
+ boxes: Tuple[Box, ...]
46
+
47
+ @property
48
+ def labeled(self) -> bool:
49
+ return len(self.boxes) > 0
50
+
51
+ def to_dict(self) -> Dict[str, Any]:
52
+ return {
53
+ "id": self.id,
54
+ "width": self.width,
55
+ "height": self.height,
56
+ "boxes": [b.to_dict() for b in self.boxes],
57
+ }
58
+
59
+
60
+ def _datasets_dir() -> Path:
61
+ path = home() / "datasets"
62
+ path.mkdir(parents=True, exist_ok=True)
63
+ return path
64
+
65
+
66
+ def list_datasets() -> List[str]:
67
+ """보관 중인 데이터셋 이름들."""
68
+ return sorted(p.name for p in _datasets_dir().iterdir() if (p / "dataset.json").exists())
69
+
70
+
71
+ def delete_dataset(name: str) -> None:
72
+ folder = _datasets_dir() / safe_name(name)
73
+ if not (folder / "dataset.json").exists():
74
+ raise FileNotFoundError(f"데이터셋이 없습니다: {name!r}")
75
+ shutil.rmtree(folder)
76
+
77
+
78
+ class Dataset:
79
+ """이름으로 여는 데이터셋. 없으면 새로 만든다.
80
+
81
+ >>> ds = Dataset("helmets")
82
+ >>> ds.add_image("site1.jpg", boxes=[("helmet", 120, 40, 260, 190)])
83
+ >>> ds.stats()
84
+ {'images': 1, 'labeled': 1, 'boxes': 1, 'classes': {'helmet': 1}}
85
+
86
+ 상자가 하나도 없는 이미지는 학습에 쓰지 않는다.
87
+ """
88
+
89
+ def __init__(self, name: str = "default", *, create: bool = True) -> None:
90
+ self.name = safe_name(name)
91
+ self.root = _datasets_dir() / self.name
92
+ self._lock = threading.RLock()
93
+ self._file = self.root / "dataset.json"
94
+ if not self._file.exists():
95
+ if not create:
96
+ raise FileNotFoundError(f"데이터셋이 없습니다: {name!r}")
97
+ (self.root / "images").mkdir(parents=True, exist_ok=True)
98
+ self._data: Dict[str, Any] = {"classes": [], "images": {}}
99
+ self._save()
100
+ else:
101
+ self._data = json.loads(self._file.read_text(encoding="utf-8"))
102
+ self._data.setdefault("classes", [])
103
+ self._data.setdefault("images", {})
104
+
105
+ def __repr__(self) -> str:
106
+ s = self.stats()
107
+ return f"<Dataset {self.name!r} · 이미지 {s['images']}장(라벨 {s['labeled']}장) · 클래스 {len(self.classes)}개>"
108
+
109
+ # ---------------------------------------------------------------- 저장
110
+ def _save(self) -> None:
111
+ tmp = self._file.with_suffix(".json.tmp")
112
+ tmp.write_text(json.dumps(self._data, ensure_ascii=False, indent=1), encoding="utf-8")
113
+ os.replace(tmp, self._file)
114
+
115
+ # -------------------------------------------------------------- 클래스
116
+ @property
117
+ def classes(self) -> List[str]:
118
+ return list(self._data["classes"])
119
+
120
+ def add_class(self, label: str) -> int:
121
+ """클래스를 추가하고 번호를 돌려준다. 이미 있으면 기존 번호."""
122
+ label = str(label).strip()
123
+ if not label:
124
+ raise ValueError("클래스 이름이 비어 있습니다.")
125
+ with self._lock:
126
+ if label not in self._data["classes"]:
127
+ self._data["classes"].append(label)
128
+ self._save()
129
+ return self._data["classes"].index(label)
130
+
131
+ def rename_class(self, old: str, new: str) -> None:
132
+ new = str(new).strip()
133
+ with self._lock:
134
+ classes = self._data["classes"]
135
+ if old not in classes:
136
+ raise KeyError(f"클래스가 없습니다: {old!r}")
137
+ if not new or (new != old and new in classes):
138
+ raise ValueError(f"쓸 수 없는 클래스 이름입니다: {new!r}")
139
+ classes[classes.index(old)] = new
140
+ for entry in self._data["images"].values():
141
+ for box in entry.get("boxes") or []:
142
+ if box["label"] == old:
143
+ box["label"] = new
144
+ self._save()
145
+
146
+ def remove_class(self, label: str) -> None:
147
+ """클래스와 그 클래스로 그린 상자를 모두 지운다."""
148
+ with self._lock:
149
+ if label not in self._data["classes"]:
150
+ raise KeyError(f"클래스가 없습니다: {label!r}")
151
+ self._data["classes"].remove(label)
152
+ for entry in self._data["images"].values():
153
+ entry["boxes"] = [b for b in entry.get("boxes") or [] if b["label"] != label]
154
+ self._save()
155
+
156
+ # -------------------------------------------------------------- 이미지
157
+ def _item(self, image_id: str, entry: Dict[str, Any]) -> ImageItem:
158
+ boxes = tuple(Box(b["label"], *b["box"]) for b in entry.get("boxes") or [])
159
+ return ImageItem(
160
+ id=image_id,
161
+ path=self.root / "images" / entry["file"],
162
+ width=entry["width"],
163
+ height=entry["height"],
164
+ boxes=boxes,
165
+ )
166
+
167
+ def images(self) -> List[ImageItem]:
168
+ with self._lock:
169
+ return [self._item(i, e) for i, e in self._data["images"].items()]
170
+
171
+ def get(self, image_id: str) -> ImageItem:
172
+ with self._lock:
173
+ if image_id not in self._data["images"]:
174
+ raise KeyError(f"이미지가 없습니다: {image_id!r}")
175
+ return self._item(image_id, self._data["images"][image_id])
176
+
177
+ def add_image(
178
+ self,
179
+ source: Any,
180
+ boxes: Optional[Iterable[BoxInput]] = None,
181
+ *,
182
+ name: Optional[str] = None,
183
+ max_side: Optional[int] = 1920,
184
+ ) -> str:
185
+ """이미지를 추가하고 id를 돌려준다.
186
+
187
+ source: 파일 경로, 바이트, PIL 이미지, 또는 BGR numpy 배열.
188
+ boxes: [(라벨, x1, y1, x2, y2), ...] 또는 [{"label":..., "box":[...]}, ...]
189
+ max_side: 긴 변이 이보다 크면 줄여서 저장한다. None이면 원본 크기 유지.
190
+ """
191
+ from .detector import load_image
192
+
193
+ if name is None and isinstance(source, (str, Path)):
194
+ name = Path(source).stem
195
+ bgr = load_image(source)
196
+ pil = Image.fromarray(bgr[:, :, ::-1])
197
+ scale = 1.0
198
+ if max_side and max(pil.size) > max_side:
199
+ scale = max_side / max(pil.size)
200
+ pil = pil.resize((round(pil.width * scale), round(pil.height * scale)), Image.LANCZOS)
201
+ with self._lock:
202
+ try:
203
+ stem = safe_name(name) if name else ""
204
+ except ValueError:
205
+ stem = ""
206
+ stem = stem or "image"
207
+ image_id = stem
208
+ while image_id in self._data["images"]:
209
+ image_id = f"{stem}-{uuid.uuid4().hex[:6]}"
210
+ filename = f"{image_id}.jpg"
211
+ pil.save(self.root / "images" / filename, quality=95)
212
+ self._data["images"][image_id] = {
213
+ "file": filename,
214
+ "width": pil.width,
215
+ "height": pil.height,
216
+ "boxes": [],
217
+ }
218
+ self._save()
219
+ if boxes:
220
+ scaled = []
221
+ for raw in boxes:
222
+ label, coords = _split_box(raw)
223
+ scaled.append((label, *[c * scale for c in coords]))
224
+ self.set_boxes(image_id, scaled)
225
+ return image_id
226
+
227
+ def remove_image(self, image_id: str) -> None:
228
+ with self._lock:
229
+ entry = self._data["images"].pop(image_id, None)
230
+ if entry is None:
231
+ raise KeyError(f"이미지가 없습니다: {image_id!r}")
232
+ self._save()
233
+ try:
234
+ (self.root / "images" / entry["file"]).unlink()
235
+ except OSError:
236
+ pass
237
+
238
+ def set_boxes(self, image_id: str, boxes: Iterable[BoxInput]) -> List[Box]:
239
+ """이미지의 상자 전체를 바꾼다. 처음 보는 라벨은 클래스로 추가한다."""
240
+ with self._lock:
241
+ if image_id not in self._data["images"]:
242
+ raise KeyError(f"이미지가 없습니다: {image_id!r}")
243
+ entry = self._data["images"][image_id]
244
+ w, h = entry["width"], entry["height"]
245
+ cleaned = []
246
+ for raw in boxes:
247
+ label, (x1, y1, x2, y2) = _split_box(raw)
248
+ x1, x2 = sorted((min(max(x1, 0.0), w), min(max(x2, 0.0), w)))
249
+ y1, y2 = sorted((min(max(y1, 0.0), h), min(max(y2, 0.0), h)))
250
+ if x2 - x1 < MIN_BOX_PX or y2 - y1 < MIN_BOX_PX:
251
+ continue
252
+ if label not in self._data["classes"]:
253
+ self._data["classes"].append(label)
254
+ cleaned.append({"label": label, "box": [round(v, 1) for v in (x1, y1, x2, y2)]})
255
+ entry["boxes"] = cleaned
256
+ self._save()
257
+ return [Box(b["label"], *b["box"]) for b in cleaned]
258
+
259
+ # ---------------------------------------------------------------- 요약
260
+ def stats(self) -> Dict[str, Any]:
261
+ with self._lock:
262
+ per_class = {label: 0 for label in self._data["classes"]}
263
+ labeled = boxes = 0
264
+ for entry in self._data["images"].values():
265
+ items = entry.get("boxes") or []
266
+ if items:
267
+ labeled += 1
268
+ boxes += len(items)
269
+ for box in items:
270
+ per_class[box["label"]] = per_class.get(box["label"], 0) + 1
271
+ return {
272
+ "images": len(self._data["images"]),
273
+ "labeled": labeled,
274
+ "boxes": boxes,
275
+ "classes": per_class,
276
+ }
277
+
278
+ # -------------------------------------------------------------- 내보내기
279
+ def export(self) -> Path:
280
+ """YOLO 학습 형식(라벨 txt, 목록, data.yaml)을 만들고 data.yaml 경로를 돌려준다.
281
+
282
+ 라벨된 이미지가 10장 이상이면 5장 중 1장을 검증용으로 떼어 둔다.
283
+ 그보다 적으면 검증에도 학습 이미지를 그대로 써서, 지표가 실제보다 좋게 나온다.
284
+ """
285
+ with self._lock:
286
+ items = [item for item in self.images() if item.labeled]
287
+ used = [c for c in self.classes if any(b.label == c for i in items for b in i.boxes)]
288
+ if not items or not used:
289
+ raise ValueError("학습에 쓸 라벨된 이미지가 없습니다. 상자를 먼저 그려 주세요.")
290
+ index = {label: n for n, label in enumerate(used)}
291
+
292
+ labels_dir = self.root / "labels"
293
+ if labels_dir.exists():
294
+ shutil.rmtree(labels_dir)
295
+ labels_dir.mkdir(parents=True)
296
+ for cache in self.root.glob("*.cache"):
297
+ cache.unlink()
298
+
299
+ for item in items:
300
+ lines = []
301
+ for b in item.boxes:
302
+ cx = (b.x1 + b.x2) / 2 / item.width
303
+ cy = (b.y1 + b.y2) / 2 / item.height
304
+ bw = (b.x2 - b.x1) / item.width
305
+ bh = (b.y2 - b.y1) / item.height
306
+ lines.append(f"{index[b.label]} {cx:.6f} {cy:.6f} {bw:.6f} {bh:.6f}")
307
+ (labels_dir / f"{item.path.stem}.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
308
+
309
+ if len(items) >= VAL_SPLIT_MIN_IMAGES:
310
+ val = items[4::5]
311
+ train = [item for n, item in enumerate(items) if n % 5 != 4]
312
+ else:
313
+ train = val = items
314
+ # 이미지가 적으면 epoch당 학습 횟수가 너무 적어 거의 배우지 못한다.
315
+ # 목록을 반복해 epoch마다 최소 MIN_TRAIN_SAMPLES장을 보게 한다(증강으로 매번 다르게 보인다).
316
+ train_paths = [str(i.path) for i in train]
317
+ repeats = -(-MIN_TRAIN_SAMPLES // len(train_paths))
318
+ (self.root / "train.txt").write_text(
319
+ "\n".join(train_paths * max(1, repeats)) + "\n", encoding="utf-8"
320
+ )
321
+ (self.root / "val.txt").write_text(
322
+ "\n".join(str(i.path) for i in val) + "\n", encoding="utf-8"
323
+ )
324
+
325
+ yaml_lines = [
326
+ f"path: {json.dumps(str(self.root), ensure_ascii=False)}",
327
+ "train: train.txt",
328
+ "val: val.txt",
329
+ "names:",
330
+ ]
331
+ yaml_lines += [f" {n}: {json.dumps(label, ensure_ascii=False)}" for label, n in index.items()]
332
+ data_yaml = self.root / "data.yaml"
333
+ data_yaml.write_text("\n".join(yaml_lines) + "\n", encoding="utf-8")
334
+ return data_yaml
335
+
336
+ def training_summary(self) -> Dict[str, Any]:
337
+ """export()가 쓸 이미지 수와 클래스."""
338
+ items = [item for item in self.images() if item.labeled]
339
+ used = [c for c in self.classes if any(b.label == c for i in items for b in i.boxes)]
340
+ return {
341
+ "images": len(items),
342
+ "classes": used,
343
+ "separate_validation": len(items) >= VAL_SPLIT_MIN_IMAGES,
344
+ }
345
+
346
+
347
+ def _split_box(raw: BoxInput) -> Tuple[str, Tuple[float, float, float, float]]:
348
+ if isinstance(raw, Box):
349
+ return raw.label, (raw.x1, raw.y1, raw.x2, raw.y2)
350
+ if isinstance(raw, dict):
351
+ label, coords = raw["label"], raw["box"]
352
+ else:
353
+ label, coords = raw[0], raw[1:]
354
+ label = str(label).strip()
355
+ if not label:
356
+ raise ValueError("상자의 라벨이 비어 있습니다.")
357
+ if len(coords) != 4:
358
+ raise ValueError(f"상자 좌표는 x1, y1, x2, y2 네 개여야 합니다: {raw!r}")
359
+ x1, y1, x2, y2 = (float(v) for v in coords)
360
+ return label, (x1, y1, x2, y2)