File size: 7,745 Bytes
c3c908f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from beat_this.inference import File2Beats
import torchaudio
import torch
from pathlib import Path
import numpy as np
from collections import Counter
import os
import argparse
from tqdm import tqdm
import multiprocessing
import librosa
import gc

def get_segments_from_wav(wav_path, device="cuda", max_duration=300):
    """์˜ค๋””์˜ค ํŒŒ์ผ์—์„œ ๋น„ํŠธ์™€ ๋‹ค์šด๋น„ํŠธ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค."""
    file2beats = File2Beats(checkpoint_path="final0", device=device, dbn=False)
    beats, downbeats = file2beats(wav_path)
    
    del file2beats
    torch.cuda.empty_cache() if device == "cuda" else None
    gc.collect()
    
    return beats, downbeats

def find_optimal_segment_length(downbeats, round_decimal=1, bar_length=4):
    """๋‹ค์šด๋น„ํŠธ ๊ฐ„๊ฒฉ๋“ค์˜ ๋ถ„ํฌ๋ฅผ ๋ถ„์„ํ•˜์—ฌ ์ตœ์ ์˜ 4๋งˆ๋”” ๊ธธ์ด์™€ ์ •์ œ๋œ ๋‹ค์šด๋น„ํŠธ ์œ„์น˜๋“ค์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค."""
    if len(downbeats) < 2:
        return 10.0, downbeats
    
    intervals = np.diff(downbeats)
    rounded_intervals = np.round(intervals, round_decimal)
    
    interval_counter = Counter(rounded_intervals)
    most_common_interval = interval_counter.most_common(1)[0][0]
    
    cleaned_downbeats = [downbeats[0]]
    
    for i in range(1, len(downbeats)):
        interval = rounded_intervals[i-1]
        if abs(interval - most_common_interval) <= most_common_interval * 0.1:
            cleaned_downbeats.append(downbeats[i])
    
    return float(most_common_interval * bar_length), np.array(cleaned_downbeats)

def process_audio_file(file_info, output_base_dir, device="cuda", max_duration=300, min_duration=30):
    """๋‹จ์ผ ์˜ค๋””์˜ค ํŒŒ์ผ์„ ์ฒ˜๋ฆฌํ•˜๊ณ  ์„ธ๊ทธ๋จผํŠธ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค."""
    audio_file, relative_path, output_subdir = file_info
    
    # ์ถœ๋ ฅ ๋””๋ ‰ํ† ๋ฆฌ ์„ค์ •
    output_dir = Path(output_base_dir) / output_subdir
    file_seg_dir = output_dir / audio_file.stem
    
    # ์ด๋ฏธ ์ฒ˜๋ฆฌ๋œ ํŒŒ์ผ์ธ์ง€ ์ฒดํฌ
    if file_seg_dir.exists() and list(file_seg_dir.glob("segment_*.mp3")):
        return -1
    
    # ํŒŒ์ผ ํฌ๊ธฐ ์ฒดํฌ
    file_size_mb = os.path.getsize(audio_file) / (1024 * 1024)
    if file_size_mb > 100:
        return 0
    
    # ์˜ค๋””์˜ค ๊ธธ์ด ์ฒดํฌ
    info = torchaudio.info(str(audio_file))
    total_duration = info.num_frames / info.sample_rate
    
    if total_duration < min_duration:
        return 0
    
    beats, downbeats = get_segments_from_wav(str(audio_file), device=device, max_duration=max_duration)
    
    if beats is None or downbeats is None or len(downbeats) == 0:
        return 0
    
    optimal_length, cleaned_downbeats = find_optimal_segment_length(downbeats)
    
    file_seg_dir.mkdir(exist_ok=True, parents=True)
    
    sample_rate = info.sample_rate
    
    # ์ตœ๋Œ€ ๊ธธ์ด ์ œํ•œ
    if total_duration > max_duration:
        total_duration = max_duration
    
    segments_count = 0
    
    # ๊ฐ ๋‹ค์šด๋น„ํŠธ์—์„œ ์‹œ์ž‘ํ•˜๋Š” ์„ธ๊ทธ๋จผํŠธ ์ƒ์„ฑ
    for i, start_time in enumerate(cleaned_downbeats):
        end_time = start_time + optimal_length
        
        if end_time > total_duration:
            continue
        
        start_frame = int(start_time * sample_rate)
        end_frame = int(end_time * sample_rate)
        
        segment, sr = torchaudio.load(
            str(audio_file), 
            frame_offset=start_frame,
            num_frames=end_frame - start_frame
        )
        
        # MP3๋กœ ์„ธ๊ทธ๋จผํŠธ ์ €์žฅ (320kbps)
        save_path = file_seg_dir / f"segment_{i}.mp3"
        torchaudio.save(
            str(save_path), 
            segment, 
            sr,
            backend = "sox",
            format="mp3",
            # # encoding="MP3",
            compression=320
        )
        segments_count += 1
        
        del segment
    
    torch.cuda.empty_cache() if device == "cuda" else None
    gc.collect()

    return segments_count

def process_file_wrapper(args):
    """multiprocessing์šฉ ๋ž˜ํผ ํ•จ์ˆ˜"""
    return process_audio_file(*args)

def segment_dataset(base_dir, output_base_dir, num_workers=4, device="cuda", max_duration=300, min_duration=30, labels=None):
    """๋ฉ€ํ‹ฐํ”„๋กœ์„ธ์‹ฑ์„ ์‚ฌ์šฉํ•œ ์„ธ๊ทธ๋จผํŠธ ์ถ”์ถœ"""
    base_path = Path(base_dir)
    
    stats = {
        "processed_files": 0,
        "extracted_segments": 0,
        "failed_files": 0,
        "skipped_files": 0,
    }
    
    # ๋ ˆ์ด๋ธ” ์„ค์ •
    if labels is None:
        labels = ["ai_cover", "real", "fake"]
    
    for label in labels:
        input_dir = base_path / label 
        
        if not input_dir.exists():
            continue
        
        # ํ•ด๋‹น ๋ ˆ์ด๋ธ” ํด๋”์—์„œ ์žฌ๊ท€์ ์œผ๋กœ ์˜ค๋””์˜ค ํŒŒ์ผ ์ฐพ๊ธฐ
        audio_files = []
        audio_extensions = {'.wav', '.mp3', '.flac', '.m4a', '.aac', '.ogg'}
        
        for file_path in input_dir.rglob('*'):
            if file_path.is_file() and file_path.suffix.lower() in audio_extensions:
                relative_path = file_path.relative_to(base_path)
                output_subdir = relative_path.parent
                audio_files.append((file_path, relative_path, output_subdir))
        
        if not audio_files:
            continue
        
        # ํŒŒ์ผ ํฌ๊ธฐ๋ณ„๋กœ ์ •๋ ฌ
        audio_files.sort(key=lambda x: os.path.getsize(x[0]))
        
        # ๋ฉ€ํ‹ฐํ”„๋กœ์„ธ์‹ฑ์œผ๋กœ ์ฒ˜๋ฆฌ
        args_list = [(file_info, output_base_dir, device, max_duration, min_duration) for file_info in audio_files]
        
        with multiprocessing.Pool(num_workers) as pool:
            results = list(tqdm(pool.imap(process_file_wrapper, args_list), 
                              total=len(args_list), desc=f"Processing {label}"))
        
        # ๊ฒฐ๊ณผ ์ง‘๊ณ„
        for segments_count in results:
            if segments_count == -1:
                stats["skipped_files"] += 1
            elif segments_count > 0:
                stats["processed_files"] += 1
                stats["extracted_segments"] += segments_count
            else:
                stats["failed_files"] += 1
    
    print(f"Successfully processed: {stats['processed_files']} files")
    print(f"Failed: {stats['failed_files']} files")
    print(f"Skipped (already processed): {stats['skipped_files']} files")
    print(f"Total segments: {stats['extracted_segments']}")
    print(f"Average segments per file: {stats['extracted_segments'] / max(1, stats['processed_files']):.2f}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Extract segments from audio files recursively")
    parser.add_argument("--input", type=str, default="/data/datasets/real_musics",
                        help="Input directory with audio files")
    parser.add_argument("--output", type=str, default="/data/datasets/ai_detection_dataset_segment",
                        help="Output directory for segments")
    parser.add_argument("--workers", type=int, default=14,
                        help="Number of parallel workers")
    parser.add_argument("--device", type=str, default="cuda",
                        help="Device for beat extraction")
    parser.add_argument("--max-duration", type=int, default=300,
                        help="Maximum audio duration in seconds")
    parser.add_argument("--min-duration", type=int, default=30,
                        help="Minimum audio duration in seconds")
    parser.add_argument("--labels", nargs='+', default=None,
                        help="Labels to process")
    
    args = parser.parse_args()
    
    segment_dataset(
        base_dir=args.input,
        output_base_dir=args.output,
        num_workers=args.workers,
        device=args.device,
        max_duration=args.max_duration,
        min_duration=args.min_duration,
        labels=args.labels
    )