import gradio as gr import librosa import numpy as np import torch import os import json import base64 import tempfile import soundfile as sf from datetime import datetime from speechbrain.inference import EncoderClassifier from huggingface_hub import login from datasets import load_dataset, Dataset # 1. 초기 세팅 및 토큰 로그인 HF_TOKEN = os.environ.get("HF_TOKEN") if HF_TOKEN: login(token=HF_TOKEN) DATASET_REPO = "easyadaptor/Voice-Matcher-DB" # 2. 화자 임베딩 모델 로드 (SpeechBrain) classifier = EncoderClassifier.from_hparams( source="speechbrain/spkrec-ecapa-voxceleb", savedir="pretrained_models/spkrec-ecapa-voxceleb" ) # 3. 오디오 특성 자동 추출 함수 def extract_audio_features(file_path): y, sr = librosa.load(file_path, sr=16000) onset_env = librosa.onset.onset_strength(y=y, sr=sr) tempo, _ = librosa.beat.beat_track(onset_envelope=onset_env, sr=sr) pitches, _ = librosa.piptrack(y=y, sr=sr) mean_pitch = np.mean(pitches[pitches > 0]) if np.any(pitches > 0) else 0 tags =[] if mean_pitch > 200: tags.append("청아한 고음") elif mean_pitch < 120: tags.append("묵직한 저음") else: tags.append("안정적인 중음") if tempo > 130: tags.append("빠르고 경쾌한 템포") elif tempo < 100: tags.append("차분하고 느린 템포") else: tags.append("적당한 템포") return tags # 4.[관리자용] 다중 파일 동시 업로드 및 병합 로직 def register_voice(actor_name, audio_files, gender, age, atmosphere, content): if not actor_name: return "성우 이름을 입력해주세요." if not audio_files: return "최소 1개 이상의 오디오 파일을 업로드해주세요." try: combined_y =[] for f in audio_files: y, sr = librosa.load(f, sr=16000) combined_y.append(y) final_signal_np = np.concatenate(combined_y, axis=0) temp_audio = tempfile.NamedTemporaryFile(delete=False, suffix=".wav") sf.write(temp_audio.name, final_signal_np, 16000) combined_audio_path = temp_audio.name auto_tags = extract_audio_features(combined_audio_path) y_final, sr_final = librosa.load(combined_audio_path, sr=16000) signal = torch.tensor(y_final).unsqueeze(0) embedding = classifier.encode_batch(signal).squeeze().tolist() with open(combined_audio_path, "rb") as f: audio_b64 = base64.b64encode(f.read()).decode("utf-8") new_data = { "actor_name":[actor_name], "tags":[json.dumps(auto_tags)], "embedding":[json.dumps(embedding)], "registered_at":[datetime.now().strftime("%Y-%m-%d %H:%M:%S")], "audio_b64":[audio_b64], "gender":[gender if gender else ""], "age":[age if age else ""], "atmosphere":[json.dumps(atmosphere if atmosphere else [])], "content":[json.dumps(content if content else [])] } try: ds = load_dataset(DATASET_REPO, split="train") if actor_name in ds["actor_name"]: ds = ds.filter(lambda x: x["actor_name"] != actor_name) msg_prefix = "🔄[정보 수정]" else: msg_prefix = "✅[신규 등록]" new_ds = Dataset.from_dict(new_data) from datasets import concatenate_datasets updated_ds = concatenate_datasets([ds, new_ds]) except Exception: updated_ds = Dataset.from_dict(new_data) msg_prefix = "✅[신규 등록]" updated_ds.push_to_hub(DATASET_REPO, token=HF_TOKEN) return f"{msg_prefix} 완료![{actor_name}] 성우의 정보가 반영되었습니다." except Exception as e: return f"❌ 오류 발생: {str(e)}" # 5.[사용자용] 유사도 분석 및 결과 오디오 반환 def match_voice(user_audio): if user_audio is None: return "분석할 오디오를 업로드하거나 녹음해주세요.", "", None target_audio = user_audio try: user_tags = extract_audio_features(target_audio) y_user, sr_user = librosa.load(target_audio, sr=16000) signal = torch.tensor(y_user).unsqueeze(0) user_embedding = classifier.encode_batch(signal).squeeze() except Exception as e: return f"❌ 오디오 분석에 실패했습니다. 유효한 음성인지 확인해주세요.\n(에러: {str(e)})", "", None try: ds = load_dataset(DATASET_REPO, split="train") except Exception: return "등록된 성우 데이터가 없습니다. 관리자 탭에서 먼저 등록해주세요.", "", None best_match = None highest_score = -1 best_audio_b64 = None cos = torch.nn.CosineSimilarity(dim=-1) for row in ds: db_emb = torch.tensor(json.loads(row["embedding"])) score = cos(user_embedding, db_emb).item() if score > highest_score: highest_score = score best_match = row["actor_name"] best_audio_b64 = row.get("audio_b64", None) similarity_percent = round((highest_score + 1) / 2 * 100, 2) ment = f"분석된 음성은 '{user_tags[0]}'과 '{user_tags[1]}'를 가지고 있습니다.\n" ment += f"이러한 특성과 성도 파형이 가장 일치하는 성우로 **[{best_match}]** 님을 추천합니다! (일치율: {similarity_percent}%)" matched_audio_path = None if best_audio_b64: try: audio_bytes = base64.b64decode(best_audio_b64) temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav") temp_file.write(audio_bytes) temp_file.close() matched_audio_path = temp_file.name except Exception: pass return ment, best_match, matched_audio_path def save_feedback(best_match, feedback_score): return f"[{best_match}] 추천에 대한 피드백({feedback_score}점)이 안전하게 저장되었습니다." # 6.[라이브러리 및 관리자 공통용] def get_actor_list(): try: ds = load_dataset(DATASET_REPO, split="train") return sorted([row["actor_name"] for row in ds]) except: return[] def get_filtered_actors(genders, ages, atmos, contents): try: ds = load_dataset(DATASET_REPO, split="train") filtered_list =[] for row in ds: r_gender = row.get("gender", "") r_age = row.get("age", "") r_atmos = json.loads(row.get("atmosphere", "[]")) if row.get("atmosphere") else[] r_content = json.loads(row.get("content", "[]")) if row.get("content") else[] if genders and r_gender not in genders: continue if ages and r_age not in ages: continue if atmos and not any(a in r_atmos for a in atmos): continue if contents and not any(c in r_content for c in contents): continue filtered_list.append(row["actor_name"]) filtered_list = sorted(filtered_list) return gr.Radio(choices=filtered_list, value=None, label="검색된 성우 선택 (바로 클릭하세요)") except: return gr.Radio(choices=[], value=None, label="검색된 성우 선택 (바로 클릭하세요)") def load_actor_details(actor_name): if not actor_name: return None, "성우를 선택해주세요." try: ds = load_dataset(DATASET_REPO, split="train") for row in ds: if row["actor_name"] == actor_name: auto_tags = ", ".join(json.loads(row.get("tags", "[]"))) r_gender = row.get("gender", "") r_age = row.get("age", "") r_atmos = ", ".join(json.loads(row.get("atmosphere", "[]"))) if row.get("atmosphere") else "" r_content = ", ".join(json.loads(row.get("content", "[]"))) if row.get("content") else "" info_text = f"**[AI 분석 특징]** {auto_tags}\n" info_text += f"**[성별/연령]** {r_gender} / {r_age}\n" info_text += f"**[분위기]** {r_atmos}\n" info_text += f"**[추천 콘텐츠]** {r_content}" if "audio_b64" in row and row["audio_b64"]: audio_bytes = base64.b64decode(row["audio_b64"]) temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav") temp_file.write(audio_bytes) temp_file.close() return temp_file.name, info_text else: return None, f"{info_text}\n\n(오디오 파일이 없는 초기 데이터입니다)" return None, "정보를 찾을 수 없습니다." except Exception as e: return None, f"오류 발생: {str(e)}" # UI 카테고리 정의 UI_GENDER =["남성", "여성"] UI_AGE =["아동", "청소년", "청년", "중년", "장년"] UI_ATMOS =["힘 있는", "밝은", "귀여운", "가벼운", "세련된", "따뜻한", "차분한", "신뢰감있는", "차가운", "감성적인", "기타"] UI_CONTENT =["다큐/리뷰", "낭독/오디오북", "기자/아나운서", "라디오/팟캐스트", "광고/이벤트", "교육/강의", "안내음성/ARS", "게임/애니", "음악/엔터테인먼트"] # 7. Gradio UI with gr.Blocks(theme=gr.themes.Soft()) as demo: with gr.Row(elem_id="header-row"): gr.Markdown("# 🎙️ AI 성우 목소리 매칭 서비스") logout_btn = gr.Button("🔒 로그아웃", size="sm", variant="secondary", scale=0, min_width=100) logout_btn.click(fn=None, inputs=None, outputs=None, js="() => { window.location.href = '/logout'; }") with gr.Tabs(): with gr.Tab("사용자 검색 (Voice Matcher)"): gr.Markdown("찾고 싶은 레퍼런스 목소리를 **직접 녹음**하거나 **파일로 업로드**해주세요.") with gr.Row(): with gr.Column(scale=1): # 🌟 sources=["upload", "microphone"] 추가로 녹음과 업로드를 동시 지원! user_audio = gr.Audio(sources=["upload", "microphone"], type="filepath", label="🎵 직접 녹음(마이크) 또는 파일 업로드") gr.HTML("""