File size: 10,106 Bytes
3cecacc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b13050
 
 
 
3cecacc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ac163
3cecacc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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 concurrent.futures


def get_segments_from_wav(wav_path, device="cuda"):
    """์˜ค๋””์˜ค ํŒŒ์ผ์—์„œ ๋น„ํŠธ์™€ ๋‹ค์šด๋น„ํŠธ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค."""
    #try:
    file2beats = File2Beats(checkpoint_path="final0", device="cuda", dbn=False)
    all_models = ["final0", "final1", "final2", "small0", "small1", "small2","single_final0", "single_final1", "single_final2"]
    beats, downbeats = file2beats(wav_path)
    if len(downbeats)==0: # downbeats๋ฅผ ๊ทธ๋ƒฅ 0 2 4..๋กœ ๋„ฃ์–ด์ฃผ์ž. ์Œ์•… ๊ธธ์ด์— ๋งž๊ฒŒ
        waveform, sample_rate = torchaudio.load(wav_path)
        duration = waveform.size(1) / sample_rate
        downbeats = np.arange(0, duration, 2)

    return beats, downbeats
    #except Exception as e:
    #    print(f"Error extracting beats from {wav_path}: {str(e)}")
    #    return None, None

def find_optimal_segment_length(downbeats, round_decimal=1, bar_length = 4):
    """๋‹ค์šด๋น„ํŠธ ๊ฐ„๊ฒฉ๋“ค์˜ ๋ถ„ํฌ๋ฅผ ๋ถ„์„ํ•˜์—ฌ ์ตœ์ ์˜ 4๋งˆ๋”” ๊ธธ์ด์™€ ์ •์ œ๋œ ๋‹ค์šด๋น„ํŠธ ์œ„์น˜๋“ค์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค."""
    if len(downbeats) < 2:
        return 10.0, downbeats  # ๊ธฐ๋ณธ 10์ดˆ ๊ธธ์ด ๋ฐ˜ํ™˜
    
    # ์—ฐ์†๋œ downbeat ๊ฐ„์˜ ๊ฐ„๊ฒฉ ๊ณ„์‚ฐ
    intervals = np.diff(downbeats)
    rounded_intervals = np.round(intervals, round_decimal)
    
    # ๊ฐ€์žฅ ํ”ํ•œ ๊ฐ„๊ฒฉ ์ฐพ๊ธฐ (1๋งˆ๋”” ๊ธธ์ด)
    interval_counter = Counter(rounded_intervals)
    most_common_interval = interval_counter.most_common(1)[0][0]
    
    # ์ •์ œ๋œ downbeat ์œ„์น˜ ์ฐพ๊ธฐ

    cleaned_downbeats = [downbeats[0]]  # ์ฒซ ๋ฒˆ์งธ ์œ„์น˜๋Š” ํ•ญ์ƒ ํฌํ•จ
    
    for i in range(1, len(downbeats)):
        interval = rounded_intervals[i-1]
        # ํ˜„์žฌ ๊ฐ„๊ฒฉ์ด ๊ฐ€์žฅ ํ”ํ•œ ๊ฐ„๊ฒฉ๊ณผ ๋น„์Šทํ•œ์ง€ ํ™•์ธ (10% ์˜ค์ฐจ ํ—ˆ์šฉ)
        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(audio_file, output_dir, temp_dir, device="cuda"):
    """๋‹จ์ผ ์˜ค๋””์˜ค ํŒŒ์ผ์„ ์ฒ˜๋ฆฌํ•˜๊ณ  ์„ธ๊ทธ๋จผํŠธ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค."""
    try:
        output_dir = Path(output_dir)  # output_dir์„ Path ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜
        beats, downbeats = get_segments_from_wav(str(audio_file), device=device)
        for bar_length in [1,2,3]:
            # ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ ํ›„ "segments_wav"๋ฅผ "segments_wav_์ˆซ์ž"๋กœ ๋Œ€์ฒด
            dir_str = str(output_dir)
            if "segments_wav" in dir_str:
                new_dir_str = dir_str.replace("segments_wav", f"segments_wav_{bar_length}")
                base_dir = Path(new_dir_str)
            else:
                # segments_wav๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ ์ฒ˜๋ฆฌ 
                base_dir = output_dir.parent / f"{output_dir.name}_{bar_length}"
                
            file_seg_dir = base_dir / audio_file.stem
            file_seg_dir.mkdir(exist_ok=True, parents=True)
                
            # ๋น„ํŠธ ์ •๋ณด ์ถ”์ถœ
            
            if beats is None or downbeats is None or len(downbeats) == 0:
                print(f"No beat information extracted for {audio_file.name}, skipping...")
                return 0
            
            # ์ตœ์ ์˜ ์„ธ๊ทธ๋จผํŠธ ๊ธธ์ด์™€ ์ •์ œ๋œ ๋‹ค์šด๋น„ํŠธ ์ฐพ๊ธฐ
            optimal_length, cleaned_downbeats = find_optimal_segment_length(downbeats, bar_length=bar_length)
            
            # ์˜ค๋””์˜ค ๋กœ๋“œ
            waveform, sample_rate = torchaudio.load(str(audio_file))
            if waveform.size(0) > 1:
                waveform = torch.mean(waveform, dim=0, keepdim=True)
            
            total_duration = waveform.size(1) / sample_rate
            segments_count = 0
            
            # ๊ฐ ๋‹ค์šด๋น„ํŠธ์—์„œ ์‹œ์ž‘ํ•˜๋Š” ์„ธ๊ทธ๋จผํŠธ ์ƒ์„ฑ
            for i, start_time in enumerate(cleaned_downbeats):
                end_time = start_time + optimal_length
                
                # ๋งˆ์ง€๋ง‰ ์„ธ๊ทธ๋จผํŠธ๊ฐ€ ํŒŒ์ผ ๊ธธ์ด๋ฅผ ์ดˆ๊ณผํ•˜๋ฉด ๊ฑด๋„ˆ๋›ฐ๊ธฐ
                if end_time > total_duration:
                    continue
                
                start_sample = int(start_time * sample_rate)
                end_sample = int(end_time * sample_rate)
                
                # ์„ธ๊ทธ๋จผํŠธ ์ถ”์ถœ ๋ฐ ์ €์žฅ
                segment = waveform[:, start_sample:end_sample]
                save_path = file_seg_dir / f"segment_{i}.wav"
                torchaudio.save(str(save_path), segment, sample_rate)
                segments_count += 1
            
            # ์ž„์‹œ ๋น„ํŠธ ์ •๋ณด ์ €์žฅ (ํ•„์š”์‹œ)
            if temp_dir:
                segments_data = {'beat': beats, 'downbeat': downbeats}
                temp_path = temp_dir / f"{audio_file.stem}_segments.npy"
                np.save(str(temp_path), segments_data)
        
        return segments_count
        
    except Exception as e:
        print(f"Error processing {audio_file.name}: {str(e)}")
        return 0

def segment_dataset(base_dir, output_base_dir, temp_dir=None, num_workers=4, device="cuda"):
    """ISMIR2025 ๋ฐ์ดํ„ฐ์…‹์˜ full_length ํด๋”์—์„œ ์„ธ๊ทธ๋จผํŠธ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค."""
    base_path = Path(base_dir)
    output_base_path = Path(output_base_dir)
    
    # ์ฒ˜๋ฆฌ ํ†ต๊ณ„
    stats = {
        "processed_files": 0,
        "extracted_segments": 0,
        "failed_files": 0
    }
    
    # ์ž„์‹œ ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ (๋น„ํŠธ ์ •๋ณด ์ €์žฅ์šฉ)
    if temp_dir:
        temp_dir = Path(temp_dir)
        temp_dir.mkdir(exist_ok=True)
    
    # Real๊ณผ Fake ์˜ค๋””์˜ค ๋ชจ๋‘ ์ฒ˜๋ฆฌ
    for label in ["real", "fake"]:
        for split in ["train", "valid", "test"]:
            input_dir = base_path / label / split
            output_dir = output_base_path / label / split
            
            if not input_dir.exists():
                print(f"Directory not found: {input_dir}")
                continue
            
            print(f"Processing {label}/{split} files...")
            audio_files = list(input_dir.glob("*.wav")) + list(input_dir.glob("*.mp3"))
            
            if not audio_files:
                print(f"No audio files found in {input_dir}")
                continue
            
            # ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ ์„ค์ •
            if num_workers > 1:
                with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
                    future_to_file = {
                        executor.submit(process_audio_file, file, output_dir, temp_dir, device): file 
                        for file in audio_files
                    }
                    
                    for future in tqdm(concurrent.futures.as_completed(future_to_file), total=len(audio_files)):
                        file = future_to_file[future]
                        try:
                            segments_count = future.result()
                            if segments_count > 0:
                                stats["processed_files"] += 1
                                stats["extracted_segments"] += segments_count
                            else:
                                stats["failed_files"] += 1
                        except Exception as e:
                            print(f"Error processing {file.name}: {str(e)}")
                            stats["failed_files"] += 1
            else:
                # ์ง๋ ฌ ์ฒ˜๋ฆฌ
                for file in tqdm(audio_files):
                    segments_count = process_audio_file(file, output_dir, temp_dir, device)
                    if segments_count > 0:
                        stats["processed_files"] += 1
                        stats["extracted_segments"] += segments_count
                    else:
                        stats["failed_files"] += 1
    
    # ์ตœ์ข… ํ†ต๊ณ„ ๋ณด๊ณ 
    print("\n=== Segmentation Summary ===")
    print(f"Successfully processed files: {stats['processed_files']}")
    print(f"Failed files: {stats['failed_files']}")
    print(f"Total extracted 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 in ISMIR2025 dataset")
    parser.add_argument("--input", type=str, default="/data/datasets/ISMIR2025/full_length_audio",
                        help="Input directory with full_length audio files")
    parser.add_argument("--output", type=str, default="/data/datasets/ISMIR2025/segments_wav",
                        help="Output directory for segments")
    parser.add_argument("--temp", type=str, default=None, 
                        help="Temporary directory for beat information (optional)")
    parser.add_argument("--workers", type=int, default=4,
                        help="Number of parallel workers")
    parser.add_argument("--device", type=str, default="cuda",
                        help="Device for beat extraction (cuda or cpu)")
    
    args = parser.parse_args()
    
    # ๋””๋ ‰ํ† ๋ฆฌ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ
    input_path = Path(args.input)
    if not input_path.exists():
        print(f"Input directory not found: {args.input}")
        # ๋‹ค๋ฅธ ๊ฐ€๋Šฅํ•œ ์œ„์น˜ ํ™•์ธ
        alternatives = [
            "/data/datasets/ISMIR2025/full_length",
            "/data/ISMIR2025/full_length_audio",
            "/data/ISMIR2025/full_length"
        ]
        
        for alt_path in alternatives:
            if os.path.exists(alt_path):
                print(f"Found alternative input path: {alt_path}")
                args.input = alt_path
                break
        else:
            print("No valid input directory found.")
            exit(1)
    
    # ์„ธ๊ทธ๋จผํŠธ ์ถ”์ถœ ์‹คํ–‰
    segment_dataset(
        base_dir=args.input,
        output_base_dir=args.output,
        temp_dir=args.temp,
        num_workers=args.workers,
        device=args.device
    )