audio
audioduration (s)
0.15
15.3
transcripts
stringlengths
1
136
input_features
sequencelengths
80
80
labels
sequencelengths
6
98
그렇죠.
[[-0.24203228950500488,-0.3051685094833374,-0.654293417930603,-0.27385568618774414,-0.21455192565917(...TRUNCATED)
[ 50258, 50264, 50359, 50363, 40650, 5837, 13, 50257 ]
민어 하 그렇습니다 그 안동은요 그러면 안동은 진짜 담을 게 많았겠네요.
[[1.0620657205581665,0.8073479533195496,0.8215495347976685,0.7173646092414856,0.7113176584243774,0.5(...TRUNCATED)
[50258,50264,50359,50363,23762,3103,3369,13773,3115,4296,9658,8309,2124,1495,16645,9658,8309,2124,71(...TRUNCATED)
어~ 가장 크게 문제가 되는 거는 추론 능력 같은 거예요.
[[0.4731941819190979,0.14038598537445068,0.1454160213470459,0.388197124004364,0.10183262825012207,0.(...TRUNCATED)
[50258,50264,50359,50363,3103,93,20283,38926,48748,18650,46821,7458,3261,19332,7707,98,21946,10005,1(...TRUNCATED)
"사무관리사라고 하지만 그까 누가 봐도 표면적으로는 노사관계 문제를 사(...TRUNCATED)
[[0.27309364080429077,0.4206721782684326,0.4921291470527649,0.3868786096572876,0.38283801078796387,0(...TRUNCATED)
[50258,50264,50359,50363,14506,18129,12222,34374,14506,6954,23286,4296,3294,33851,8649,22983,41065,2(...TRUNCATED)
"제가 아까 물어봤잖아요 현장에 누가 먼저 달려가느냐고 지휘본부가는 게 (...TRUNCATED)
[[0.2513716220855713,0.45008713006973267,0.4485553503036499,0.4764915704727173,0.4824037551879883,0.(...TRUNCATED)
[50258,50264,50359,50363,49149,25289,44558,23560,13928,17505,4573,1517,33851,20749,20738,5743,1453,3(...TRUNCATED)
"타임 시리즈로 볼 수 있으니까 암흑 물질 분포가 어떻게 변했는지를 알 수(...TRUNCATED)
[[-0.4861382246017456,-0.3633284568786621,-0.4523385763168335,-0.43620598316192627,-0.39381420612335(...TRUNCATED)
[50258,50264,50359,50363,25439,13311,24452,2250,9760,2196,1955,18001,4446,44489,1298,242,9428,239,14(...TRUNCATED)
"어 쪼꼼 재밌는 게 그~ 아까 세종실록을 말씀하셨는데 정악이라고 얘기가 (...TRUNCATED)
[[-0.05356419086456299,0.37625980377197266,0.37875813245773315,0.3823813199996948,0.4244530200958252(...TRUNCATED)
[50258,50264,50359,50363,3103,451,103,120,33019,120,31224,1098,7845,4296,93,25289,11605,17273,1995,2(...TRUNCATED)
십사억 오천만 원
[[-0.15784919261932373,-0.5404387712478638,-0.7886273860931396,-0.7463316917419434,-0.52428472042083(...TRUNCATED)
[ 50258, 50264, 50359, 50363, 32061, 5727, 19824, 5175, 4758, 2163, 6478, 13499, 50257 ]
"왜 그래야 되는 것인지 모르겠고 참으면 두 개를 준다는 거였나요 나중에 (...TRUNCATED)
[[-0.7182977199554443,-0.18580234050750732,-0.18482351303100586,-0.37207162380218506,-0.138718366622(...TRUNCATED)
[50258,50264,50359,50363,5485,250,7080,4248,18650,4431,37194,20502,5137,1313,18255,10819,11915,1777,(...TRUNCATED)
네.
[[-0.08348464965820312,-0.13583874702453613,-0.24430465698242188,0.035359978675842285,-0.51782917976(...TRUNCATED)
[ 50258, 50264, 50359, 50363, 17507, 13, 50257 ]

여전히 컬럼 제거가 필요해 보여요.

  • 다음 코드를 실행시켜 제작했어요.
import os
import json
from pydub import AudioSegment
from tqdm import tqdm
import re
from datasets import Audio, Dataset, DatasetDict, load_from_disk, concatenate_datasets
from transformers import WhisperFeatureExtractor, WhisperTokenizer
import pandas as pd
import shutil

# 사용자 지정 변수를 설정해요.

# DATA_DIR = '/mnt/a/maxseats/(주의-원본-680GB)주요 영역별 회의 음성인식 데이터' # 데이터셋이 저장된 폴더
DATA_DIR = '/mnt/a/maxseats/(주의-원본)split_files/set_1'  # 첫 10GB 테스트

# 원천, 라벨링 데이터 폴더 지정
json_base_dir = DATA_DIR
audio_base_dir = DATA_DIR
output_dir = '/mnt/a/maxseats/(주의-원본)clips_set_1'                     # 가공된 데이터셋이 저장될 폴더
token = "hf_"                     # 허깅페이스 토큰
CACHE_DIR = '/mnt/a/maxseats/.cache'                                # 허깅페이스 캐시 저장소 지정
dataset_name = "maxseats/aihub-464-preprocessed-680GB-set-1"              # 허깅페이스에 올라갈 데이터셋 이름
model_name = "SungBeom/whisper-small-ko"                            # 대상 모델 / "openai/whisper-base"


batch_size = 3000   # 배치사이즈 지정, 8000이면 에러 발생
os.environ['HF_DATASETS_CACHE'] = CACHE_DIR
'''
데이터셋 경로를 지정해서
하나의 폴더에 mp3, txt 파일로 추출해요. (clips_set_i 폴더)
추출 과정에서 원본 파일은 자동으로 삭제돼요. (저장공간 절약을 위해)
'''

# 캐시 디렉토리가 없으면 생성
os.makedirs(CACHE_DIR, exist_ok=True)

def bracket_preprocess(text):
    
    # 정규 표현식을 사용하여 패턴 제거
    text = re.sub(r'/\([^\)]+\)', '', text)  # /( *) 패턴 제거, /(...) 형식 제거
    text = re.sub(r'[()]', '', text)         # 개별적으로 등장하는 ( 및 ) 제거
    
    return text.strip()

def process_audio_and_subtitle(json_path, audio_base_dir, output_dir):
    # JSON 파일 읽기
    with open(json_path, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    # 메타데이터에서 오디오 파일 이름 추출
    title = data['metadata']['title']
    
    # 각 TS, VS 폴더에서 해당 오디오 파일을 찾기
    audio_file = None
    for root, _, files in os.walk(audio_base_dir):
        for file in files:
            if file == title + '.wav':
                audio_file = os.path.join(root, file)
                break
        if audio_file:
            break
    
    # 오디오 파일 로드
    if not audio_file or not os.path.exists(audio_file):
        print(f"Audio file {audio_file} does not exist.")
        return
    
    audio = AudioSegment.from_mp3(audio_file)
    audio_length_ms = len(audio)
    
    # 발화 데이터 처리
    for utterance in data['utterance']:
        start_time = int(float(utterance['start']) * 1000.0)# 밀리초로 변환
        end_time = int(float(utterance['end']) * 1000.0)    # 밀리초로 변환
        text = bracket_preprocess(utterance['form'])   # 괄호 전처리
        
        if not text:    # 비어 있으면 수행 x
            continue
        
        # 비정상적인 start_time 및 end_time 감지
        if start_time < 0 or end_time > audio_length_ms or start_time >= end_time:
            continue
        
        
        # 오디오 클립 추출
        audio_clip = audio[start_time:end_time]
        
        # 파일 이름 설정
        clip_id = utterance['id']
        audio_output_path = os.path.join(output_dir, clip_id + '.mp3')
        text_output_path = os.path.join(output_dir, clip_id + '.txt')
        
        # 오디오 클립 저장
        audio_clip.export(audio_output_path, format='mp3')
        
        # 괄호 전처리 텍스트 파일 저장
        with open(text_output_path, 'w', encoding='utf-8') as f:
            f.write(text)

    # 오디오 파일 삭제
    os.remove(audio_file)
    os.remove(audio_file.replace('.wav', '.txt'))
    print(f"Deleted audio file: {audio_file}")

def process_all_files(json_base_dir, audio_base_dir, output_dir):
    json_files = []
    
    # JSON 파일 목록 생성
    for root, dirs, files in os.walk(json_base_dir):
        for file in files:
            if file.endswith('.json'):
                json_files.append(os.path.join(root, file))
    
    # JSON 파일 처리
    for json_file in tqdm(json_files, desc="Processing JSON files"):
        process_audio_and_subtitle(json_file, audio_base_dir, output_dir)
        
        # 완료 후 JSON 파일 삭제
        os.remove(json_file)
        print(f"Deleted JSON file: {json_file}")

# 디렉토리 생성
os.makedirs(output_dir, exist_ok=True)

# 프로세스 실행
process_all_files(json_base_dir, audio_base_dir, output_dir)



'''
가공된 mp3, txt 데이터를 학습 가능한 허깅페이스 데이터셋 형태로 변환해요.
'''

# 캐시 디렉토리 설정
os.environ['HF_HOME'] = CACHE_DIR
os.environ["HF_DATASETS_CACHE"] = CACHE_DIR
feature_extractor = WhisperFeatureExtractor.from_pretrained(model_name, cache_dir=CACHE_DIR)
tokenizer = WhisperTokenizer.from_pretrained(model_name, language="Korean", task="transcribe", cache_dir=CACHE_DIR)

def exclude_json_files(file_names: list) -> list:
    # .json으로 끝나는 원소 제거
    return [file_name for file_name in file_names if not file_name.endswith('.json')]


def get_label_list(directory):
    # 빈 리스트 생성
    label_files = []

    # 디렉토리 내 파일 목록 불러오기
    for filename in os.listdir(directory):
        # 파일 이름이 '.txt'로 끝나는지 확인
        if filename.endswith('.txt'):
            label_files.append(os.path.join(directory, filename))

    return label_files


def get_audio_list(directory):
    # 빈 리스트 생성
    audio_files = []

    # 디렉토리 내 파일 목록 불러오기
    for filename in os.listdir(directory):
        # 파일 이름이 '.wav'나 '.mp3'로 끝나는지 확인
        if filename.endswith('.wav') or filename.endswith('mp3'):
            audio_files.append(os.path.join(directory, filename))

    return audio_files

def prepare_dataset(batch):
    # 오디오 파일을 16kHz로 로드
    audio = batch["audio"]

    # input audio array로부터 log-Mel spectrogram 변환
    batch["input_features"] = feature_extractor(audio["array"], sampling_rate=audio["sampling_rate"]).input_features[0]


    # target text를 label ids로 변환
    batch["labels"] = tokenizer(batch["transcripts"]).input_ids
    
    # 'input_features'와 'labels'만 포함한 새로운 딕셔너리 생성
    return {"input_features": batch["input_features"], "labels": batch["labels"]}


label_data = get_label_list(output_dir)
audio_data = get_audio_list(output_dir)

transcript_list = []
for label in tqdm(label_data):
    with open(label, 'r', encoding='UTF8') as f:
        line = f.readline()
        transcript_list.append(line)

df = pd.DataFrame(data=transcript_list, columns = ["transcript"]) # 정답 label
df['audio_data'] = audio_data # 오디오 파일 경로

# 오디오 파일 경로를 dict의 "audio" 키의 value로 넣고 이를 데이터셋으로 변환
# 이때, Whisper가 요구하는 사양대로 Sampling rate는 16,000으로 설정한다.
# 데이터셋 배치 처리
batches = []
for i in tqdm(range(0, len(df), batch_size), desc="Processing batches"):
    batch_df = df.iloc[i:i+batch_size]
    ds = Dataset.from_dict(
        {"audio": [path for path in batch_df["audio_data"]],
         "transcripts": [transcript for transcript in batch_df["transcript"]]}
    ).cast_column("audio", Audio(sampling_rate=16000))
    
    batch_datasets = DatasetDict({"batch": ds})
    batch_datasets = batch_datasets.map(prepare_dataset, num_proc=1)
    batch_datasets.remove_columns(['audio', 'transcripts'])    # 불필요한 부분 제거
    batch_datasets.save_to_disk(os.path.join(CACHE_DIR, f'batch_{i//batch_size}'))
    batches.append(os.path.join(CACHE_DIR, f'batch_{i//batch_size}'))
    print(f"Processed and saved batch {i//batch_size}")

# 모든 배치 데이터셋 로드
loaded_batches = [load_from_disk(path) for path in batches]

# 배치 데이터셋을 하나로 병합
full_dataset = concatenate_datasets([batch['batch'] for batch in loaded_batches])

# 데이터셋을 훈련 데이터와 테스트 데이터, 밸리데이션 데이터로 분할
train_testvalid = full_dataset.train_test_split(test_size=0.2)
test_valid = train_testvalid["test"].train_test_split(test_size=0.5)
datasets = DatasetDict(
    {"train": train_testvalid["train"],
     "test": test_valid["test"],
     "valid": test_valid["train"]}
)



'''
허깅페이스 로그인 후, 최종 데이터셋을 업로드해요.
'''
# datasets.save_to_disk('/mnt/a/maxseats/preprocessed_cache.arrow')
# datasets.push_to_hub(dataset_name, token=token)

while True:
    
    if token =="exit":
        break
    
    try:
        datasets.push_to_hub(dataset_name, token=token)
        print(f"Dataset {dataset_name} pushed to hub successfully. 넘나 축하.")
        break
    except Exception as e:
        print(f"Failed to push dataset: {e}")
        token = input("Please enter your Hugging Face API token: ")

# 캐시 디렉토리 삭제
shutil.rmtree(CACHE_DIR)
print(f"Deleted cache directory: {CACHE_DIR}")
Downloads last month
5
Edit dataset card

Models trained or fine-tuned on maxseats/aihub-464-preprocessed-680GB-set-1