File size: 7,466 Bytes
b4586d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""데이터셋을 라벨별 <label>/raw/ + <label>/clips_2s/ 구조로 재편한다.

이전 구조는 원본이 수집처별 폴더(개소리, esc50, donateacry_…)에 흩어져 있고
전처리 클립은 data_augmented/ 아래 따로 있어서, 한 라벨의 데이터를 보려면
두 군데를 봐야 했다. 재편 후:

    edge_audio_dataset/
    ├── 총/
    │   ├── raw/       297   (원본, 8~22초)
    │   └── clips_2s/  4,257 (2초 분할·증강)
    ├── baby_cry/
    │   ├── raw/       190   (donateacry 188 + esc50 2)
    │   └── clips_2s/  2,808
    ├── background/clips_2s/  (무음 판정분, raw 없음)
    └── docs/          README.md, 데이터 추가 안내…txt

폴더명은 CSV의 label 값을 그대로 쓴다(개소리 -> dog_bark 등). 라벨 안에서
파일명 stem 이 유일한 것은 사전 확인했으므로 평탄화해도 충돌하지 않는다.

CSV의 경로 컬럼도 <label>/raw/<basename> 으로 함께 고쳐야 매니페스트가 깨지지
않는다. --dry-run 으로 먼저 계획을 확인할 것.
"""
from __future__ import annotations

import argparse
import csv
import shutil
import unicodedata
from collections import Counter, defaultdict
from pathlib import Path

ROOT = Path(__file__).resolve().parent
LABEL_CSV = "integrated_test_labels_0716.csv"

# 재편 후 경로를 다시 써야 하는 CSV: 파일명 -> 경로 컬럼
CSVS_TO_REWRITE = {
    "dataset_labels.csv": "file_path",
    "integrated_test_labels.csv": "filename",
    "integrated_test_labels_0716.csv": "filename",
    "integrated_all_0716.csv": "filename",
    "integrated_target4_0716.csv": "filename",
}

DOCS = ["데이터 추가 안내0716김예원.txt"]
AUG_DIR = "data_augmented"
STAGING = "processed_all"          # 파이프라인 출력(임시)
OBSOLETE = ["processed", "processed_target4"]  # 삭제 대상


def nfc(s: str) -> str:
    return unicodedata.normalize("NFC", s)


def resolve(rel: str) -> Path | None:
    for form in (None, "NFC", "NFD"):
        p = ROOT / (rel if form is None else unicodedata.normalize(form, rel))
        if p.exists():
            return p
    return None


def plan_raw_moves() -> tuple[dict[Path, Path], Counter]:
    """CSV의 (경로, 라벨)에서 원본 파일 이동 계획을 만든다."""
    moves: dict[Path, Path] = {}
    stats: Counter = Counter()
    dest_seen: dict[Path, Path] = {}
    with open(ROOT / LABEL_CSV, encoding="utf-8-sig", newline="") as f:
        for row in csv.DictReader(f):
            rel, label = row["filename"].strip(), nfc(row["label"].strip())
            src = resolve(rel)
            if src is None:
                continue  # 디스크에 없는 원본은 건너뛴다
            dest = ROOT / label / "raw" / src.name
            if dest in dest_seen and dest_seen[dest] != src:
                raise RuntimeError(f"이름 충돌: {src}{dest_seen[dest]} 가 모두 {dest} 로 감")
            dest_seen[dest] = src
            moves[src] = dest
            stats[label] += 1
    return moves, stats


def plan_clip_moves(staging: Path) -> tuple[dict[Path, Path], Counter]:
    """파이프라인 출력 <staging>/<label>/*.wav -> <label>/clips_2s/*.wav"""
    moves: dict[Path, Path] = {}
    stats: Counter = Counter()
    for label_dir in sorted(p for p in staging.iterdir() if p.is_dir()):
        label = nfc(label_dir.name)
        for wav in label_dir.glob("*.wav"):
            moves[wav] = ROOT / label / "clips_2s" / wav.name
            stats[label] += 1
    return moves, stats


def rewrite_csvs(dry_run: bool) -> None:
    """경로 컬럼을 <label>/raw/<basename> 으로 고친다."""
    for name, path_col in CSVS_TO_REWRITE.items():
        src = ROOT / name
        if not src.exists():
            print(f"  [skip] {name} 없음")
            continue
        with open(src, encoding="utf-8-sig", newline="") as f:
            reader = csv.DictReader(f)
            fields = reader.fieldnames or []
            rows = list(reader)
        label_col = "label"
        changed = 0
        for r in rows:
            label = nfc(r[label_col].strip())
            base = Path(nfc(r[path_col].strip())).name
            new = f"{label}/raw/{base}"
            if new != r[path_col]:
                r[path_col] = new
                changed += 1
        print(f"  {name}: {changed}/{len(rows)} 행 경로 수정")
        if not dry_run:
            with open(src, "w", encoding="utf-8", newline="") as f:
                w = csv.DictWriter(f, fieldnames=fields)
                w.writeheader()
                w.writerows(rows)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--dry-run", action="store_true")
    args = ap.parse_args()
    dry = args.dry_run
    tag = "[DRY] " if dry else ""

    staging = ROOT / AUG_DIR / STAGING
    if not staging.exists():
        raise FileNotFoundError(f"파이프라인 출력이 없습니다: {staging}")

    raw_moves, raw_stats = plan_raw_moves()
    clip_moves, clip_stats = plan_clip_moves(staging)

    print(f"{tag}원본 이동 {len(raw_moves)}개, 클립 이동 {len(clip_moves)}개\n")
    print(f"{'label':14s} {'raw':>7s} {'clips_2s':>10s}")
    for label in sorted(set(raw_stats) | set(clip_stats)):
        print(f"{label:14s} {raw_stats[label]:7d} {clip_stats[label]:10d}")

    print(f"\n{tag}1) 원본 -> <label>/raw/")
    for src, dest in raw_moves.items():
        if not dry:
            dest.parent.mkdir(parents=True, exist_ok=True)
            shutil.move(str(src), str(dest))

    print(f"{tag}2) 클립 -> <label>/clips_2s/")
    for src, dest in clip_moves.items():
        if not dry:
            dest.parent.mkdir(parents=True, exist_ok=True)
            shutil.move(str(src), str(dest))

    print(f"{tag}3) CSV 경로 재작성")
    rewrite_csvs(dry)

    print(f"{tag}4) 문서 -> docs/")
    docs_dir = ROOT / "docs"
    for rel in DOCS + [f"{AUG_DIR}/README.md"]:
        src = resolve(rel)
        if src is None:
            print(f"  [skip] {rel} 없음")
            continue
        print(f"  {rel} -> docs/{src.name}")
        if not dry:
            docs_dir.mkdir(exist_ok=True)
            shutil.move(str(src), str(docs_dir / src.name))

    print(f"{tag}5) 빈 폴더 · 구 전처리 결과 정리")
    for name in OBSOLETE:
        p = ROOT / AUG_DIR / name
        if p.exists():
            print(f"  삭제: {AUG_DIR}/{name}")
            if not dry:
                shutil.rmtree(p)
    for d in sorted(p for p in ROOT.iterdir() if p.is_dir()):
        if d.name in {"docs", AUG_DIR} or nfc(d.name) in set(raw_stats) | set(clip_stats):
            continue
        remaining = list(d.rglob("*")) if d.exists() else []
        if not any(p.is_file() for p in remaining):
            print(f"  빈 폴더 삭제: {d.name}")
            if not dry:
                shutil.rmtree(d)
        else:
            # esc50/ 의 JSON sidecar 가 대표적. 1~6절 prepare_manifest.py 가
            # data-root 전체에서 **/*.json 로 긁어 쓰므로 위치는 상관없지만
            # 삭제하면 안 된다.
            kept = [p.suffix or "dir" for p in remaining if p.is_file()]
            print(f"  [보존] {d.name}: wav 외 파일 {len(kept)}개 남음 {sorted(set(kept))}")
    if not dry:
        shutil.rmtree(staging, ignore_errors=True)

    print(f"\n{tag}완료")


if __name__ == "__main__":
    main()