AI 및 Data Analysis

[Alzheimer] 녹음 파일 불러와서 이미지로 변환하기

doraemin_dev 2025. 3. 23. 18:11

AI-Hub에서 데이터 신청을 했다.

AI-Hub

https://www.aihub.or.kr/aihubdata/data/view.do?pageIndex=1&currMenu=&topMenu=&srchOptnCnd=OPTNCND001&searchKeyword=%EC%B9%98%EB%A7%A4+%EC%9D%8C%EC%84%B1&srchDetailCnd=DETAILCND001&srchOrder=ORDER001&srchPagePer=20&aihubDataSe=data&dataSetSn=217

 

AI-Hub

온라인 안심존 데이터 ? ※온라인 안심존 : 보안이 보장된 온라인 네트워크를 통해 집, 연구실, 사무실 등 어디서나 접속하여 데이터에 접근하고 분석

www.aihub.or.kr


녹음 파일 경로

IB-APPS 폴더 안에 여러개의 폴더가 있다. 각 폴더 안에, 11가지 종류의 음성 파일이 있다. 각 음성파일은 4가지 버젼으로 이루어져 있다.

데이터 선정

AI 모델 학습에  _R.flac 파일 사용하자. (R.json이 존재하니)

 

음성 데이터 가져와서, 이미지 형태로 변환하기

import os
import json
import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np

def Mel_Spectrogram(wav_file, save_file, sr=48000):
    y, _ = librosa.load(wav_file, sr=sr)
    S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128)
    S_dB = librosa.power_to_db(S, ref=np.max)

    plt.figure(figsize=(10, 4))
    librosa.display.specshow(S_dB, sr=sr, x_axis='time', y_axis='mel')
    plt.axis('off')
    plt.tight_layout()
    plt.savefig(save_file + '.png', bbox_inches='tight', pad_inches=0)
    plt.close()

# 경로 설정
base_path = '/tf/dataset/IB-APPS'
save_base_path = '/tf/dataset/result_wav_to_mfcc'
sr = 48000

# 기존 구조 유지하면서 확장
for folder in os.listdir(base_path):
    folder_path = os.path.join(base_path, folder)
    if not os.path.isdir(folder_path):
        continue

    file_list = os.listdir(folder_path)
    count = 1

    for file_name in file_list:
        if file_name.endswith('_R.flac'):
            wav_file = os.path.join(folder_path, file_name)
            
            # 파일명에서 num 추출
            try:
                num = file_name.split('_')[-2]  # 예: 0019..._0_R.flac → '0'
            except IndexError:
                print(f"[!] num 추출 실패: {file_name}")
                continue

            # JSON 경로 찾기 및 subject_type 추출
            json_name = file_name.replace('_R.flac', '_R.json')
            json_path = os.path.join(folder_path, json_name)
            if not os.path.exists(json_path):
                print(f"[!] JSON 파일 없음: {json_path}")
                continue

            try:
                with open(json_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    label = data['DATA']['subject_type']
            except Exception as e:
                print(f"[!] JSON 읽기 실패: {json_path} → {e}")
                continue

            # 저장 경로 및 파일명 설정
            save_path = os.path.join(save_base_path, num)
            os.makedirs(save_path, exist_ok=True)

            save_file_name = file_name.replace('_R.flac', f'_label{label}')
            save_file_path = os.path.join(save_path, save_file_name)

            # Mel-Spectrogram 저장
            Mel_Spectrogram(wav_file, save_file_path, sr)
            print(f"[✓] {file_name} → {save_file_name}.png 저장 완료 ({count})")
            count += 1

 

 

 

import os

def get_clean_audio_files(base_dir):
    clean_audio_files = []

    # IB-APPS 폴더 하위의 각 세부 폴더 순회
    for patient_folder in os.listdir(base_dir):
        patient_path = os.path.join(base_dir, patient_folder)

        if os.path.isdir(patient_path):
            # 하위 폴더 안의 모든 파일 중 _F.flac 파일만 선택
            for file in os.listdir(patient_path):
                if file.endswith('_F.flac'):
                    full_path = os.path.join(patient_path, file)
                    clean_audio_files.append(full_path)
    
    return clean_audio_files