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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
- split: valid
|
35 |
path: data/valid-*
|
36 |
---
|
37 |
+
### 여전히 컬럼 제거가 필요해 보여요.
|
38 |
+
- 다음 코드를 실행시켜 제작했어요.
|
39 |
+
```
|
40 |
+
import os
|
41 |
+
import json
|
42 |
+
from pydub import AudioSegment
|
43 |
+
from tqdm import tqdm
|
44 |
+
import re
|
45 |
+
from datasets import Audio, Dataset, DatasetDict, load_from_disk, concatenate_datasets
|
46 |
+
from transformers import WhisperFeatureExtractor, WhisperTokenizer
|
47 |
+
import pandas as pd
|
48 |
+
import shutil
|
49 |
+
|
50 |
+
# 사용자 지정 변수를 설정해요.
|
51 |
+
|
52 |
+
# DATA_DIR = '/mnt/a/maxseats/(주의-원본-680GB)주요 영역별 회의 음성인식 데이터' # 데이터셋이 저장된 폴더
|
53 |
+
DATA_DIR = '/mnt/a/maxseats/(주의-원본)split_files/set_1' # 첫 10GB 테스트
|
54 |
+
|
55 |
+
# 원천, 라벨링 데이터 폴더 지정
|
56 |
+
json_base_dir = DATA_DIR
|
57 |
+
audio_base_dir = DATA_DIR
|
58 |
+
output_dir = '/mnt/a/maxseats/(주의-원본)clips_set_1' # 가공된 데이터셋이 저장될 폴더
|
59 |
+
token = "hf_" # 허깅페이스 토큰
|
60 |
+
CACHE_DIR = '/mnt/a/maxseats/.cache' # 허깅페이스 캐시 저장소 지정
|
61 |
+
dataset_name = "maxseats/aihub-464-preprocessed-680GB-set-1" # 허깅페이스에 올라갈 데이터셋 이름
|
62 |
+
model_name = "SungBeom/whisper-small-ko" # 대상 모델 / "openai/whisper-base"
|
63 |
+
|
64 |
+
|
65 |
+
batch_size = 3000 # 배치사이즈 지정, 8000이면 에러 발생
|
66 |
+
os.environ['HF_DATASETS_CACHE'] = CACHE_DIR
|
67 |
+
'''
|
68 |
+
데이터셋 경로를 지정해서
|
69 |
+
하나의 폴더에 mp3, txt 파일로 추출해요. (clips_set_i 폴더)
|
70 |
+
추출 과정에서 원본 파일은 자동으로 삭제돼요. (저장공간 절약을 위해)
|
71 |
+
'''
|
72 |
+
|
73 |
+
# 캐시 디렉토리가 없으면 생성
|
74 |
+
os.makedirs(CACHE_DIR, exist_ok=True)
|
75 |
+
|
76 |
+
def bracket_preprocess(text):
|
77 |
+
|
78 |
+
# 정규 표현식을 사용하여 패턴 제거
|
79 |
+
text = re.sub(r'/\([^\)]+\)', '', text) # /( *) 패턴 제거, /(...) 형식 제거
|
80 |
+
text = re.sub(r'[()]', '', text) # 개별적으로 등장하는 ( 및 ) 제거
|
81 |
+
|
82 |
+
return text.strip()
|
83 |
+
|
84 |
+
def process_audio_and_subtitle(json_path, audio_base_dir, output_dir):
|
85 |
+
# JSON 파일 읽기
|
86 |
+
with open(json_path, 'r', encoding='utf-8') as f:
|
87 |
+
data = json.load(f)
|
88 |
+
|
89 |
+
# 메타데이터에서 오디오 파일 이름 추출
|
90 |
+
title = data['metadata']['title']
|
91 |
+
|
92 |
+
# 각 TS, VS 폴더에서 해당 오디오 파일을 찾기
|
93 |
+
audio_file = None
|
94 |
+
for root, _, files in os.walk(audio_base_dir):
|
95 |
+
for file in files:
|
96 |
+
if file == title + '.wav':
|
97 |
+
audio_file = os.path.join(root, file)
|
98 |
+
break
|
99 |
+
if audio_file:
|
100 |
+
break
|
101 |
+
|
102 |
+
# 오디오 파일 로드
|
103 |
+
if not audio_file or not os.path.exists(audio_file):
|
104 |
+
print(f"Audio file {audio_file} does not exist.")
|
105 |
+
return
|
106 |
+
|
107 |
+
audio = AudioSegment.from_mp3(audio_file)
|
108 |
+
audio_length_ms = len(audio)
|
109 |
+
|
110 |
+
# 발화 데이터 처리
|
111 |
+
for utterance in data['utterance']:
|
112 |
+
start_time = int(float(utterance['start']) * 1000.0)# 밀리초로 변환
|
113 |
+
end_time = int(float(utterance['end']) * 1000.0) # 밀리초로 변환
|
114 |
+
text = bracket_preprocess(utterance['form']) # 괄호 전처리
|
115 |
+
|
116 |
+
if not text: # 비어 있으면 수행 x
|
117 |
+
continue
|
118 |
+
|
119 |
+
# 비정상적인 start_time 및 end_time 감지
|
120 |
+
if start_time < 0 or end_time > audio_length_ms or start_time >= end_time:
|
121 |
+
continue
|
122 |
+
|
123 |
+
|
124 |
+
# 오디오 클립 추출
|
125 |
+
audio_clip = audio[start_time:end_time]
|
126 |
+
|
127 |
+
# 파일 이름 설정
|
128 |
+
clip_id = utterance['id']
|
129 |
+
audio_output_path = os.path.join(output_dir, clip_id + '.mp3')
|
130 |
+
text_output_path = os.path.join(output_dir, clip_id + '.txt')
|
131 |
+
|
132 |
+
# 오디오 클립 저장
|
133 |
+
audio_clip.export(audio_output_path, format='mp3')
|
134 |
+
|
135 |
+
# 괄호 전처리 텍스트 파일 저장
|
136 |
+
with open(text_output_path, 'w', encoding='utf-8') as f:
|
137 |
+
f.write(text)
|
138 |
+
|
139 |
+
# 오디오 파일 삭제
|
140 |
+
os.remove(audio_file)
|
141 |
+
os.remove(audio_file.replace('.wav', '.txt'))
|
142 |
+
print(f"Deleted audio file: {audio_file}")
|
143 |
+
|
144 |
+
def process_all_files(json_base_dir, audio_base_dir, output_dir):
|
145 |
+
json_files = []
|
146 |
+
|
147 |
+
# JSON 파일 목록 생성
|
148 |
+
for root, dirs, files in os.walk(json_base_dir):
|
149 |
+
for file in files:
|
150 |
+
if file.endswith('.json'):
|
151 |
+
json_files.append(os.path.join(root, file))
|
152 |
+
|
153 |
+
# JSON 파일 처리
|
154 |
+
for json_file in tqdm(json_files, desc="Processing JSON files"):
|
155 |
+
process_audio_and_subtitle(json_file, audio_base_dir, output_dir)
|
156 |
+
|
157 |
+
# 완료 후 JSON 파일 삭제
|
158 |
+
os.remove(json_file)
|
159 |
+
print(f"Deleted JSON file: {json_file}")
|
160 |
+
|
161 |
+
# 디렉토리 생성
|
162 |
+
os.makedirs(output_dir, exist_ok=True)
|
163 |
+
|
164 |
+
# 프로세스 실행
|
165 |
+
process_all_files(json_base_dir, audio_base_dir, output_dir)
|
166 |
+
|
167 |
+
|
168 |
+
|
169 |
+
'''
|
170 |
+
가공된 mp3, txt 데이터를 학습 ���능한 허깅페이스 데이터셋 형태로 변환해요.
|
171 |
+
'''
|
172 |
+
|
173 |
+
# 캐시 디렉토리 설정
|
174 |
+
os.environ['HF_HOME'] = CACHE_DIR
|
175 |
+
os.environ["HF_DATASETS_CACHE"] = CACHE_DIR
|
176 |
+
feature_extractor = WhisperFeatureExtractor.from_pretrained(model_name, cache_dir=CACHE_DIR)
|
177 |
+
tokenizer = WhisperTokenizer.from_pretrained(model_name, language="Korean", task="transcribe", cache_dir=CACHE_DIR)
|
178 |
+
|
179 |
+
def exclude_json_files(file_names: list) -> list:
|
180 |
+
# .json으로 끝나는 원소 제거
|
181 |
+
return [file_name for file_name in file_names if not file_name.endswith('.json')]
|
182 |
+
|
183 |
+
|
184 |
+
def get_label_list(directory):
|
185 |
+
# 빈 리스트 생성
|
186 |
+
label_files = []
|
187 |
+
|
188 |
+
# 디렉토리 내 파일 목록 불러오기
|
189 |
+
for filename in os.listdir(directory):
|
190 |
+
# 파일 이름이 '.txt'로 끝나는지 확인
|
191 |
+
if filename.endswith('.txt'):
|
192 |
+
label_files.append(os.path.join(directory, filename))
|
193 |
+
|
194 |
+
return label_files
|
195 |
+
|
196 |
+
|
197 |
+
def get_audio_list(directory):
|
198 |
+
# 빈 리스트 생성
|
199 |
+
audio_files = []
|
200 |
+
|
201 |
+
# 디렉토리 내 파일 목록 불러오기
|
202 |
+
for filename in os.listdir(directory):
|
203 |
+
# 파일 이름이 '.wav'나 '.mp3'로 끝나는지 확인
|
204 |
+
if filename.endswith('.wav') or filename.endswith('mp3'):
|
205 |
+
audio_files.append(os.path.join(directory, filename))
|
206 |
+
|
207 |
+
return audio_files
|
208 |
+
|
209 |
+
def prepare_dataset(batch):
|
210 |
+
# 오디오 파일을 16kHz로 로드
|
211 |
+
audio = batch["audio"]
|
212 |
+
|
213 |
+
# input audio array로부터 log-Mel spectrogram 변환
|
214 |
+
batch["input_features"] = feature_extractor(audio["array"], sampling_rate=audio["sampling_rate"]).input_features[0]
|
215 |
+
|
216 |
+
|
217 |
+
# target text를 label ids로 변환
|
218 |
+
batch["labels"] = tokenizer(batch["transcripts"]).input_ids
|
219 |
+
|
220 |
+
# 'input_features'와 'labels'만 포함한 새로운 딕셔너리 생성
|
221 |
+
return {"input_features": batch["input_features"], "labels": batch["labels"]}
|
222 |
+
|
223 |
+
|
224 |
+
label_data = get_label_list(output_dir)
|
225 |
+
audio_data = get_audio_list(output_dir)
|
226 |
+
|
227 |
+
transcript_list = []
|
228 |
+
for label in tqdm(label_data):
|
229 |
+
with open(label, 'r', encoding='UTF8') as f:
|
230 |
+
line = f.readline()
|
231 |
+
transcript_list.append(line)
|
232 |
+
|
233 |
+
df = pd.DataFrame(data=transcript_list, columns = ["transcript"]) # 정답 label
|
234 |
+
df['audio_data'] = audio_data # 오디오 파일 경로
|
235 |
+
|
236 |
+
# 오디오 파일 경로를 dict의 "audio" 키의 value로 넣고 이를 데이터셋으로 변환
|
237 |
+
# 이때, Whisper가 요구하는 사양대로 Sampling rate는 16,000으로 설정한다.
|
238 |
+
# 데이터셋 배치 처리
|
239 |
+
batches = []
|
240 |
+
for i in tqdm(range(0, len(df), batch_size), desc="Processing batches"):
|
241 |
+
batch_df = df.iloc[i:i+batch_size]
|
242 |
+
ds = Dataset.from_dict(
|
243 |
+
{"audio": [path for path in batch_df["audio_data"]],
|
244 |
+
"transcripts": [transcript for transcript in batch_df["transcript"]]}
|
245 |
+
).cast_column("audio", Audio(sampling_rate=16000))
|
246 |
+
|
247 |
+
batch_datasets = DatasetDict({"batch": ds})
|
248 |
+
batch_datasets = batch_datasets.map(prepare_dataset, num_proc=1)
|
249 |
+
batch_datasets.remove_columns(['audio', 'transcripts']) # 불필요한 부분 제거
|
250 |
+
batch_datasets.save_to_disk(os.path.join(CACHE_DIR, f'batch_{i//batch_size}'))
|
251 |
+
batches.append(os.path.join(CACHE_DIR, f'batch_{i//batch_size}'))
|
252 |
+
print(f"Processed and saved batch {i//batch_size}")
|
253 |
+
|
254 |
+
# 모든 배치 데이터셋 로드
|
255 |
+
loaded_batches = [load_from_disk(path) for path in batches]
|
256 |
+
|
257 |
+
# 배치 데이터셋을 하나로 병합
|
258 |
+
full_dataset = concatenate_datasets([batch['batch'] for batch in loaded_batches])
|
259 |
+
|
260 |
+
# 데이터셋을 훈련 데이터와 테스트 데이터, 밸리데이션 데이터로 분할
|
261 |
+
train_testvalid = full_dataset.train_test_split(test_size=0.2)
|
262 |
+
test_valid = train_testvalid["test"].train_test_split(test_size=0.5)
|
263 |
+
datasets = DatasetDict(
|
264 |
+
{"train": train_testvalid["train"],
|
265 |
+
"test": test_valid["test"],
|
266 |
+
"valid": test_valid["train"]}
|
267 |
+
)
|
268 |
+
|
269 |
+
|
270 |
+
|
271 |
+
'''
|
272 |
+
허깅페이스 로그인 후, 최종 데이터셋을 업로드해요.
|
273 |
+
'''
|
274 |
+
# datasets.save_to_disk('/mnt/a/maxseats/preprocessed_cache.arrow')
|
275 |
+
# datasets.push_to_hub(dataset_name, token=token)
|
276 |
+
|
277 |
+
while True:
|
278 |
+
|
279 |
+
if token =="exit":
|
280 |
+
break
|
281 |
+
|
282 |
+
try:
|
283 |
+
datasets.push_to_hub(dataset_name, token=token)
|
284 |
+
print(f"Dataset {dataset_name} pushed to hub successfully. 넘나 축하.")
|
285 |
+
break
|
286 |
+
except Exception as e:
|
287 |
+
print(f"Failed to push dataset: {e}")
|
288 |
+
token = input("Please enter your Hugging Face API token: ")
|
289 |
+
|
290 |
+
# 캐시 디렉토리 삭제
|
291 |
+
shutil.rmtree(CACHE_DIR)
|
292 |
+
print(f"Deleted cache directory: {CACHE_DIR}")
|
293 |
+
```
|