maxseats commited on
Commit
3e12539
·
verified ·
1 Parent(s): 237b3d1

Update README.md

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