roboaudit 0.2.2__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.
roboaudit/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """RoboAudit - LeRobot 데이터셋 건강검진 CLI."""
2
+
3
+ __version__ = "0.2.2"
roboaudit/__main__.py ADDED
@@ -0,0 +1,120 @@
1
+ """RoboAudit CLI.
2
+
3
+ 사용법:
4
+ python -m roboaudit <dataset_dir> --out <dir> [--sample-frames N]
5
+ [--share-bundle]
6
+ python -m roboaudit share <result.json> [--out <share_bundle.json>]
7
+
8
+ 출력: report.html / result.json / clean_index.json / review_index.json
9
+ (--share-bundle 시 share_bundle.json 추가)
10
+
11
+ 공유 묶음(share bundle)은 동의 기반(opt-in) 익명 요약이다. 자동 전송은
12
+ 없고, 기본값은 OFF이며, 데이터셋 이름·경로·과제 원문은 포함되지 않는다
13
+ (share.py 참조).
14
+
15
+ 종료 코드:
16
+ 0 = 감사 완료 (전 검사가 전체 범위를 검사함; 결함 발견 여부와 무관)
17
+ 3 = 감사는 끝났으나 불완전 (일부 검사가 부분 실행/오류 — 성적표에 명시됨)
18
+ 2 = 입력 오류 (데이터셋 폴더·meta/info.json 없음, 출력 폴더가 데이터셋 안쪽,
19
+ share 대상 result.json 없음/형식 오류)
20
+ 1 = 예상하지 못한 실행 실패
21
+ """
22
+ import argparse
23
+ import json
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ from .audit import audit_dataset
28
+ from .report import write_outputs
29
+ from .share import bundle_from_result_file, write_bundle
30
+
31
+
32
+ def _share_main(argv):
33
+ """`roboaudit share <result.json>` — 기존 결과에서 익명 묶음 생성."""
34
+ ap = argparse.ArgumentParser(
35
+ prog="roboaudit share",
36
+ description="감사 결과(result.json)에서 동의 기반 익명 공유 "
37
+ "묶음(share_bundle.json)을 만든다. 전송은 하지 않는다.")
38
+ ap.add_argument("result_json", help="감사 출력 폴더의 result.json 경로")
39
+ ap.add_argument("--out", default=None,
40
+ help="묶음 출력 경로 (기본: result.json 옆 share_bundle.json)")
41
+ args = ap.parse_args(argv)
42
+ src = Path(args.result_json)
43
+ if not src.exists():
44
+ print(f"error: {src} 가 없습니다", file=sys.stderr)
45
+ return 2
46
+ try:
47
+ bundle = bundle_from_result_file(src)
48
+ except (json.JSONDecodeError, OSError) as exc:
49
+ print(f"error: result.json을 읽을 수 없습니다: {exc}", file=sys.stderr)
50
+ return 2
51
+ out = Path(args.out) if args.out else src.parent / "share_bundle.json"
52
+ out.parent.mkdir(parents=True, exist_ok=True)
53
+ out.write_text(json.dumps(bundle, indent=2, ensure_ascii=False),
54
+ encoding="utf-8")
55
+ print(f"share_bundle: {out}")
56
+ print("이 파일은 익명 요약만 담고 있으며, 어디에도 자동 전송되지 "
57
+ "않습니다. 제출 여부는 본인이 결정하세요.")
58
+ return 0
59
+
60
+
61
+ def main(argv=None):
62
+ argv = list(sys.argv[1:] if argv is None else argv)
63
+ if argv and argv[0] == "share":
64
+ return _share_main(argv[1:])
65
+ ap = argparse.ArgumentParser(prog="roboaudit",
66
+ description="LeRobot 데이터셋 건강검진")
67
+ ap.add_argument("dataset", help="LeRobot 데이터셋 폴더 (v2.1 / v3.0)")
68
+ ap.add_argument("--out", default=None,
69
+ help="출력 폴더 (기본: <dataset>_audit)")
70
+ ap.add_argument("--sample-frames", type=int, default=None,
71
+ help="표본 모드: 에피소드당 영상 통계를 최대 N프레임 "
72
+ "균등 표본으로 계산 (대용량용, 기본: 전수)")
73
+ ap.add_argument("--share-bundle", action="store_true",
74
+ help="동의 기반 익명 공유 묶음(share_bundle.json)도 "
75
+ "출력 폴더에 생성 (기본: 생성 안 함, 전송 없음)")
76
+ args = ap.parse_args(argv)
77
+
78
+ root = Path(args.dataset)
79
+ if not (root / "meta" / "info.json").exists():
80
+ print(f"error: {root} 에 meta/info.json 이 없습니다", file=sys.stderr)
81
+ return 2
82
+ out_dir = Path(args.out) if args.out else Path(f"{root.name}_audit")
83
+ # 배포 안전 (추가 검토 4): 출력이 입력 데이터셋 안쪽이면 원본을 오염시키므로 거부.
84
+ root_resolved = root.resolve()
85
+ out_resolved = out_dir.resolve()
86
+ if out_resolved == root_resolved or root_resolved in out_resolved.parents:
87
+ print(f"error: 출력 폴더({out_dir})가 데이터셋 폴더({root}) 안쪽입니다. "
88
+ "원본 오염 방지를 위해 거부합니다 — 데이터셋 바깥 폴더를 지정하세요",
89
+ file=sys.stderr)
90
+ return 2
91
+ try:
92
+ result = audit_dataset(root, sample_frames=args.sample_frames)
93
+ except Exception as exc:
94
+ print(f"error: 감사 실행 실패: {type(exc).__name__}: {exc}",
95
+ file=sys.stderr)
96
+ return 1
97
+ paths = write_outputs(result, out_dir)
98
+ if args.share_bundle:
99
+ paths["share_bundle"] = str(write_bundle(
100
+ result, out_dir / "share_bundle.json"))
101
+ s = result["summary"]
102
+ print(f"dataset : {s['dataset']} (LeRobot {s['format']}, "
103
+ f"{s['total_episodes']} episodes)")
104
+ print(f"score : {result['score']}/100 grade {result['grade']} "
105
+ f"(deduction {result['total_deduction']}, findings {len(result['findings'])})")
106
+ print(f"clean : {len(result['clean_episodes'])} episodes / "
107
+ f"excluded {len(result['excluded_episodes'])} / "
108
+ f"review {len(result['review_episodes'])}")
109
+ if result["incomplete_audit"]:
110
+ print("warning : 불완전한 감사 — 일부 검사가 전체 범위를 검사하지 "
111
+ "못했습니다 (성적표 실행 상태 참조)", file=sys.stderr)
112
+ for k, v in paths.items():
113
+ print(f"{k:11s}: {v}")
114
+ if result["errors"]:
115
+ print(f"errors : {result['errors']}", file=sys.stderr)
116
+ return 3 if result["incomplete_audit"] else 0
117
+
118
+
119
+ if __name__ == "__main__":
120
+ sys.exit(main())
roboaudit/audit.py ADDED
@@ -0,0 +1,197 @@
1
+ """감사 실행: 데이터셋 1개에 검사 12종을 돌려 결과 dict를 만든다.
2
+
3
+ 보강(5단계):
4
+ - 검사 상태 분리: 검사마다 run_status(complete/partial/not_applicable/error)와
5
+ 실제 검사 범위(scope)를 기록한다. 디코딩 실패가 '정상'으로 집계되지 않으며,
6
+ 필수 검사가 불완전하면 incomplete_audit=True 로 종합에 명시한다.
7
+ - 처분 3단계: 에피소드를 exclude/review/keep으로 나눈다 (disposition.py).
8
+ - 감점 Top 3 요인과 재현 기록(run_manifest)을 결과에 포함한다.
9
+ """
10
+ import hashlib
11
+ import shutil
12
+ import time
13
+ from pathlib import Path
14
+
15
+ from . import __version__
16
+ from .checks12 import CHECKS12, CHECK_NAMES, RULES_VERSION, SEVERITY, TH, Ctx
17
+ from .disposition import BORDERLINE_MARGIN, episode_dispositions, margin_ratio
18
+ from .scoring import score_findings
19
+
20
+ VIDEO_CHECKS = {"V1", "V2", "V3"}
21
+
22
+ # 고지 문구 (추가 검토 2·5): 성적표와 result.json에 항상/조건부로 동봉한다.
23
+ NOTICE_SCOPE = ("범위 고지: RoboAudit는 데이터셋의 구조·통계적 이상을 검사하는 "
24
+ "도구이며, 학습 성능이나 로봇의 안전성을 보증하지 않습니다.")
25
+ NOTICE_A2 = ("A2(급격한 점프) 해석 고지: A2 보류(review)는 측정값이 경계 근처라는 "
26
+ "뜻이며, 이 검사만으로는 기록 결함과 운용 특성(프레임 드롭·빠른 동작 등)을 "
27
+ "구분할 수 없습니다. 보류는 무해하다는 판정이 아닙니다.")
28
+ NOTICE_SAMPLE = ("표본 모드 고지: 표본 결과는 근사치입니다. 표본에서는 프레임 간격이 "
29
+ "벌어져 V1 정지 판정이 전수보다 엄격해질 수 있고 경계 구간의 정지를 "
30
+ "놓칠 수 있으므로, 최종 판정은 전수 재실행을 권장합니다.")
31
+
32
+
33
+ def input_fingerprint(root: Path) -> dict:
34
+ """입력 지문: 전 파일 (상대경로, 크기, SHA-256) 목록의 SHA-256."""
35
+ entries = []
36
+ total_bytes = 0
37
+ for p in sorted(root.rglob("*")):
38
+ if p.is_file():
39
+ data = p.read_bytes()
40
+ total_bytes += len(data)
41
+ entries.append(f"{p.relative_to(root)}\0{len(data)}\0"
42
+ f"{hashlib.sha256(data).hexdigest()}")
43
+ digest = hashlib.sha256("\n".join(entries).encode()).hexdigest()
44
+ return {"algorithm": "sha256(file list: relpath, size, sha256)",
45
+ "value": digest, "n_files": len(entries),
46
+ "total_bytes": total_bytes}
47
+
48
+
49
+ def _check_status(code, ctx, errors, data_ok, data_bad):
50
+ """검사 1개의 (run_status, scope) 산정."""
51
+ reader = ctx.reader
52
+ total = len(reader.episodes)
53
+ if code in errors:
54
+ return "error", f"검사 실행 오류: {errors[code]}"
55
+ if code in VIDEO_CHECKS:
56
+ if not reader.video_keys:
57
+ return "not_applicable", "선언된 영상 피처 없음"
58
+ dec = reader.decode_summary()
59
+ parts, complete = [], True
60
+ for key in reader.video_keys:
61
+ d = dec.get(key, {"episodes_decoded": 0, "episodes_failed": [],
62
+ "episodes_missing_file": []})
63
+ n_fail = len(d["episodes_failed"])
64
+ n_miss = len(d["episodes_missing_file"])
65
+ parts.append(f"{key}: 디코딩 {d['episodes_decoded']}/{total}"
66
+ f", 실패 {n_fail}, 파일없음 {n_miss}")
67
+ if n_fail or n_miss:
68
+ complete = False
69
+ return ("complete" if complete else "partial"), "; ".join(parts)
70
+ # 데이터 기반 검사
71
+ if total == 0:
72
+ return "not_applicable", "에피소드 없음"
73
+ if data_bad:
74
+ return "partial", f"데이터 읽음 {len(data_ok)}/{total} 에피소드"
75
+ return "complete", f"데이터 {total}/{total} 에피소드"
76
+
77
+
78
+ def audit_dataset(root, sample_frames=None) -> dict:
79
+ root = Path(root)
80
+ t0 = time.time()
81
+ ctx = Ctx(root, sample_frames=sample_frames)
82
+ reader = ctx.reader
83
+ findings, errors = [], {}
84
+ for code, fn in CHECKS12.items():
85
+ try:
86
+ findings.extend(fn(ctx))
87
+ except Exception as exc: # 검사 하나가 죽어도 전체는 계속
88
+ errors[code] = f"{type(exc).__name__}: {exc}"
89
+ findings.sort(key=lambda f: (f["check"],
90
+ -1 if f["episode_index"] is None else f["episode_index"]))
91
+ score, grade, per_check = score_findings(findings)
92
+
93
+ # 처분 3단계 (findings는 그대로, 처분만 분리)
94
+ for f in findings:
95
+ m = margin_ratio(f)
96
+ f["margin_ratio"] = None if m is None else round(min(m, 999.0), 3)
97
+ dispo = episode_dispositions(findings)
98
+ all_eps = [e["episode_index"] for e in reader.episodes]
99
+ flagged = {}
100
+ for f in findings:
101
+ if f["episode_index"] is not None:
102
+ flagged.setdefault(f["episode_index"], []).append(f["check"])
103
+ clean_eps = [ep for ep in all_eps if ep not in flagged]
104
+ excluded_eps = [ep for ep in all_eps if dispo.get(ep) == "exclude"]
105
+ review_eps = [ep for ep in all_eps if dispo.get(ep) == "review"]
106
+
107
+ # 검사 상태·범위
108
+ data_ok, data_bad = reader.data_availability()
109
+ check_table = []
110
+ for code in CHECKS12:
111
+ run_status, scope = _check_status(code, ctx, errors, data_ok, data_bad)
112
+ check_table.append({
113
+ "check": code,
114
+ "name": CHECK_NAMES[code],
115
+ "severity": SEVERITY[code],
116
+ "findings": per_check.get(code, {}).get("findings", 0),
117
+ "deduction": per_check.get(code, {}).get("deduction", 0),
118
+ "status": "FAIL" if per_check.get(code, {}).get("findings", 0) else "PASS",
119
+ "run_status": run_status,
120
+ "scope": scope,
121
+ "error": errors.get(code),
122
+ })
123
+ incomplete = any(c["run_status"] in ("partial", "error")
124
+ for c in check_table)
125
+
126
+ # 감점 Top 3 요인
127
+ total_deduction = sum(c["deduction"] for c in check_table)
128
+ ranked = sorted((c for c in check_table if c["deduction"] > 0),
129
+ key=lambda c: (-c["deduction"], c["check"]))
130
+ top_factors = [{
131
+ "check": c["check"], "name": c["name"], "findings": c["findings"],
132
+ "deduction": c["deduction"],
133
+ "share_pct": round(100.0 * c["deduction"] / total_deduction, 1)
134
+ if total_deduction else 0.0,
135
+ } for c in ranked[:3]]
136
+
137
+ info = reader.info
138
+ # 고지: 범위 고지는 항상, A2·표본 고지는 해당할 때만.
139
+ notices = [NOTICE_SCOPE]
140
+ if any(f["check"] == "A2" for f in findings):
141
+ notices.append(NOTICE_A2)
142
+ if sample_frames:
143
+ notices.append(NOTICE_SAMPLE)
144
+ summary = {
145
+ "dataset": root.name,
146
+ "path": str(root),
147
+ "format": reader.version,
148
+ "video_key": reader.video_key,
149
+ "video_keys": reader.video_keys,
150
+ "robot_type": info.get("robot_type"),
151
+ "total_episodes": len(all_eps),
152
+ "total_frames_meta": int(info.get("total_frames", 0)),
153
+ "fps": info.get("fps"),
154
+ "total_tasks": int(info.get("total_tasks", 0)),
155
+ "incomplete_audit": incomplete,
156
+ "sample_frames": sample_frames,
157
+ }
158
+ decode = reader.decode_summary()
159
+ manifest = {
160
+ "tool": {"name": "roboaudit", "version": __version__},
161
+ "rules_version": RULES_VERSION,
162
+ "thresholds": TH,
163
+ "disposition": {"borderline_margin": BORDERLINE_MARGIN,
164
+ "note": f"margin_ratio >= {BORDERLINE_MARGIN} -> exclude, "
165
+ f"< {BORDERLINE_MARGIN} or info-only -> review"},
166
+ "input_fingerprint": input_fingerprint(root),
167
+ "video_decode": {
168
+ "backends_available": {"opencv": True,
169
+ "ffmpeg": shutil.which("ffmpeg")},
170
+ "per_camera": decode,
171
+ },
172
+ "sample_frames": sample_frames,
173
+ "audit_seconds": round(time.time() - t0, 1),
174
+ }
175
+ return {
176
+ "summary": summary,
177
+ "score": score,
178
+ "grade": grade,
179
+ "total_deduction": total_deduction,
180
+ "incomplete_audit": incomplete,
181
+ "notices": notices,
182
+ "top_factors": top_factors,
183
+ "checks": check_table,
184
+ "findings": findings,
185
+ "errors": errors,
186
+ "manifest": manifest,
187
+ "clean_episodes": clean_eps,
188
+ "excluded_episodes": [
189
+ {"episode_index": ep, "checks": sorted(set(flagged[ep]))}
190
+ for ep in excluded_eps
191
+ ],
192
+ "review_episodes": [
193
+ {"episode_index": ep, "checks": sorted(set(flagged[ep]))}
194
+ for ep in review_eps
195
+ ],
196
+ "dispositions": {str(ep): dispo.get(ep, "keep") for ep in all_eps},
197
+ }