Update app.py
Browse files
app.py
CHANGED
|
@@ -5,219 +5,162 @@ from transformers import pipeline
|
|
| 5 |
from datetime import datetime
|
| 6 |
import os
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
# AI 모델 초기화
|
| 9 |
-
|
| 10 |
-
model="kresnik/wav2vec2-large-xlsr-korean")
|
| 11 |
-
emotion_classifier = pipeline("audio-classification",
|
| 12 |
-
model="MIT/ast-finetuned-speech-commands-v2")
|
| 13 |
-
text_analyzer = pipeline("sentiment-analysis",
|
| 14 |
-
model="nlptown/bert-base-multilingual-uncased-sentiment")
|
| 15 |
|
| 16 |
def create_interface():
|
| 17 |
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
| 18 |
-
# 상태
|
| 19 |
state = gr.State({
|
| 20 |
-
"stage": "intro",
|
| 21 |
-
"user_name": "",
|
| 22 |
"reflections": [],
|
| 23 |
-
"
|
| 24 |
-
"
|
| 25 |
-
"generated_images": []
|
| 26 |
})
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
with gr.
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
| 54 |
)
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
label="현재 순간의 감상을 적어주세요",
|
| 60 |
-
lines=3
|
| 61 |
-
)
|
| 62 |
-
save_reflection = gr.Button("감상 저장")
|
| 63 |
-
reflections_display = gr.Dataframe(
|
| 64 |
-
headers=["시간", "감상", "감정"],
|
| 65 |
-
label="기록된 감상들"
|
| 66 |
-
)
|
| 67 |
-
|
| 68 |
-
# 3. 기원
|
| 69 |
-
with gr.Tab("기원", id="prayer"):
|
| 70 |
-
gr.Markdown("## 기원 - 목소리로 전하기")
|
| 71 |
-
with gr.Row():
|
| 72 |
-
# 음성 입력
|
| 73 |
-
voice_input = gr.Audio(
|
| 74 |
-
label="나누고 싶은 이야기를 들려주세요",
|
| 75 |
-
sources=["microphone"],
|
| 76 |
-
type="filepath",
|
| 77 |
-
interactive=True
|
| 78 |
)
|
| 79 |
-
|
| 80 |
-
# 분석 결과 표시
|
| 81 |
-
with gr.Column():
|
| 82 |
-
analysis_output = gr.JSON(
|
| 83 |
-
label="음성 분석 결과"
|
| 84 |
-
)
|
| 85 |
-
text_output = gr.Textbox(
|
| 86 |
-
label="인식된 텍스트",
|
| 87 |
-
interactive=False
|
| 88 |
-
)
|
| 89 |
-
emotion_output = gr.Textbox(
|
| 90 |
-
label="감정 분석",
|
| 91 |
-
interactive=False
|
| 92 |
-
)
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
# 함수 정의
|
| 110 |
-
def start_journey(name
|
| 111 |
-
"""여정 시작
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
| 121 |
try:
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
"energy": float(np.mean(librosa.feature.rms(y=y))),
|
| 131 |
-
"pitch_mean": float(np.mean(librosa.pitch_tuning(y))),
|
| 132 |
"tempo": float(librosa.beat.tempo(y)[0]),
|
| 133 |
-
"mfcc": librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13).mean(axis=1).tolist(),
|
| 134 |
"zero_crossing_rate": float(np.mean(librosa.feature.zero_crossing_rate(y)))
|
| 135 |
}
|
| 136 |
-
|
| 137 |
-
# 2. 음성 감정 분석
|
| 138 |
-
emotion_result = emotion_classifier(y)
|
| 139 |
-
|
| 140 |
-
# 3. 음성-텍스트 변환
|
| 141 |
-
text_result = speech_recognizer(y)
|
| 142 |
|
| 143 |
-
#
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
"text_sentiment": text_sentiment
|
| 152 |
-
}
|
| 153 |
-
|
| 154 |
-
# 프롬프트 생성
|
| 155 |
-
prompt = generate_art_prompt(analysis_result)
|
| 156 |
-
state["current_prompt"] = prompt
|
| 157 |
|
| 158 |
return (
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
f"텍스트 감정: {text_sentiment['label']} ({text_sentiment['score']:.2f})"
|
| 164 |
)
|
| 165 |
-
|
| 166 |
except Exception as e:
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
def save_reflection(text, state):
|
| 170 |
-
"""감상 저장 함수"""
|
| 171 |
-
if not text.strip():
|
| 172 |
-
return state, state["reflections"]
|
| 173 |
-
|
| 174 |
-
current_time = datetime.now().strftime("%H:%M:%S")
|
| 175 |
-
sentiment = text_analyzer(text)[0]
|
| 176 |
-
new_reflection = [current_time, text, sentiment["label"]]
|
| 177 |
-
|
| 178 |
-
state["reflections"].append(new_reflection)
|
| 179 |
-
return state, state["reflections"]
|
| 180 |
-
|
| 181 |
-
def generate_art_prompt(analysis):
|
| 182 |
-
"""분석 결과를 바탕으로 예술적 프롬프트 생성"""
|
| 183 |
-
emotion = analysis["voice_emotion"]["label"]
|
| 184 |
-
energy = analysis["acoustic_analysis"]["energy"]
|
| 185 |
-
text_sentiment = analysis["text_sentiment"]["label"]
|
| 186 |
-
|
| 187 |
-
colors = {
|
| 188 |
-
"happy": "따뜻한 노란색과 주황색",
|
| 189 |
-
"sad": "차분한 파랑색과 보라색",
|
| 190 |
-
"angry": "강렬한 빨강색과 검정색",
|
| 191 |
-
"neutral": "부드러운 회색과 베이지색"
|
| 192 |
-
}
|
| 193 |
-
|
| 194 |
-
prompt = f"한국 전통 민화 스타일로, {emotion}의 감정을 {colors.get(emotion, '자연스러운 색상')}으로 표현한 추상화. "
|
| 195 |
-
prompt += f"음성의 에너지({energy:.2f})를 채도로 표현하고, "
|
| 196 |
-
prompt += f"텍스트의 감정({text_sentiment})을 구도에 반영."
|
| 197 |
-
|
| 198 |
-
return prompt
|
| 199 |
|
| 200 |
# 이벤트 연결
|
| 201 |
-
|
| 202 |
fn=start_journey,
|
| 203 |
-
inputs=[name_input
|
| 204 |
-
outputs=[
|
| 205 |
)
|
| 206 |
-
|
| 207 |
-
|
| 208 |
fn=save_reflection,
|
| 209 |
inputs=[reflection_input, state],
|
| 210 |
outputs=[state, reflections_display]
|
| 211 |
)
|
| 212 |
-
|
| 213 |
voice_input.change(
|
| 214 |
fn=analyze_voice,
|
| 215 |
inputs=[voice_input, state],
|
| 216 |
-
outputs=[
|
| 217 |
)
|
| 218 |
|
| 219 |
return app
|
| 220 |
|
|
|
|
| 221 |
if __name__ == "__main__":
|
| 222 |
-
|
| 223 |
-
|
|
|
|
| 5 |
from datetime import datetime
|
| 6 |
import os
|
| 7 |
|
| 8 |
+
# 전역 변수 설정
|
| 9 |
+
SAMPLE_RATE = 16000 # 샘플링 레이트 고정
|
| 10 |
+
N_MELS = 64 # mel 필터 수 조정
|
| 11 |
+
|
| 12 |
# AI 모델 초기화
|
| 13 |
+
text_analyzer = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
def create_interface():
|
| 16 |
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
| 17 |
+
# 상태 변수
|
| 18 |
state = gr.State({
|
|
|
|
|
|
|
| 19 |
"reflections": [],
|
| 20 |
+
"user_name": "",
|
| 21 |
+
"analyses": []
|
|
|
|
| 22 |
})
|
| 23 |
|
| 24 |
+
# 헤더
|
| 25 |
+
header = gr.Markdown("# 디지털 굿판")
|
| 26 |
+
user_display = gr.Markdown("")
|
| 27 |
+
|
| 28 |
+
with gr.Tabs() as tabs:
|
| 29 |
+
# 입장 탭
|
| 30 |
+
with gr.Tab("입장") as intro_tab:
|
| 31 |
+
gr.Markdown("""
|
| 32 |
+
# 디지털 굿판에 오신 것을 환영합니다
|
| 33 |
+
온천천의 디지털 치유 공간으로 들어가보세요.
|
| 34 |
+
""")
|
| 35 |
+
name_input = gr.Textbox(label="이름을 알려주세요")
|
| 36 |
+
start_btn = gr.Button("여정 시작하기")
|
| 37 |
+
|
| 38 |
+
# 청신 탭
|
| 39 |
+
with gr.Tab("청신") as cleansing_tab:
|
| 40 |
+
with gr.Row():
|
| 41 |
+
# 음악 플레이어
|
| 42 |
+
audio = gr.Audio(
|
| 43 |
+
value="assets/main_music.mp3",
|
| 44 |
+
type="filepath",
|
| 45 |
+
label="온천천의 소리",
|
| 46 |
+
interactive=True
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
with gr.Column():
|
| 50 |
+
reflection_input = gr.Textbox(
|
| 51 |
+
label="현재 순간의 감상을 적어주세요",
|
| 52 |
+
lines=3
|
| 53 |
)
|
| 54 |
+
save_btn = gr.Button("감상 저장하기")
|
| 55 |
+
reflections_display = gr.Dataframe(
|
| 56 |
+
headers=["시간", "감상", "감정"],
|
| 57 |
+
label="기록된 감상들"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
+
# 기원 탭
|
| 61 |
+
with gr.Tab("기원") as prayer_tab:
|
| 62 |
+
with gr.Row():
|
| 63 |
+
voice_input = gr.Audio(
|
| 64 |
+
label="나누고 싶은 이야기를 들려주세요",
|
| 65 |
+
sources=["microphone"],
|
| 66 |
+
type="filepath"
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
with gr.Column():
|
| 70 |
+
text_output = gr.Textbox(label="인식된 텍스트")
|
| 71 |
+
emotion_output = gr.Textbox(label="감정 분석")
|
| 72 |
+
audio_features = gr.JSON(label="음성 특성 분석")
|
| 73 |
+
|
| 74 |
+
# 송신 탭
|
| 75 |
+
with gr.Tab("송신") as sharing_tab:
|
| 76 |
+
prompt_display = gr.Textbox(label="생성된 프롬프트")
|
| 77 |
+
gallery = gr.Gallery(label="시각화 결과")
|
| 78 |
|
| 79 |
# 함수 정의
|
| 80 |
+
def start_journey(name):
|
| 81 |
+
"""여정 시작"""
|
| 82 |
+
if name.strip():
|
| 83 |
+
welcome_text = f"# 환영합니다, {name}님"
|
| 84 |
+
return welcome_text, gr.update(selected="청신")
|
| 85 |
+
return "이름을 입력해주세요", gr.update(selected="입장")
|
| 86 |
+
|
| 87 |
+
def save_reflection(text, state_data):
|
| 88 |
+
"""감상 저장"""
|
| 89 |
+
if not text.strip():
|
| 90 |
+
return state_data, []
|
| 91 |
+
|
| 92 |
try:
|
| 93 |
+
current_time = datetime.now().strftime("%H:%M:%S")
|
| 94 |
+
sentiment = text_analyzer(text)[0]
|
| 95 |
+
new_reflection = [current_time, text, sentiment["label"]]
|
| 96 |
+
|
| 97 |
+
if "reflections" not in state_data:
|
| 98 |
+
state_data["reflections"] = []
|
| 99 |
+
|
| 100 |
+
state_data["reflections"].append(new_reflection)
|
| 101 |
+
return state_data, state_data["reflections"]
|
| 102 |
+
except Exception as e:
|
| 103 |
+
print(f"Error in save_reflection: {str(e)}")
|
| 104 |
+
return state_data, []
|
| 105 |
|
| 106 |
+
def analyze_voice(audio_path, state_data):
|
| 107 |
+
"""음성 분석"""
|
| 108 |
+
if audio_path is None:
|
| 109 |
+
return None, None, None, state_data
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
# 오디오 로드 및 리샘플링
|
| 113 |
+
y, sr = librosa.load(audio_path, sr=SAMPLE_RATE)
|
| 114 |
+
|
| 115 |
+
# 기본 특성 추출
|
| 116 |
+
features = {
|
| 117 |
"energy": float(np.mean(librosa.feature.rms(y=y))),
|
|
|
|
| 118 |
"tempo": float(librosa.beat.tempo(y)[0]),
|
|
|
|
| 119 |
"zero_crossing_rate": float(np.mean(librosa.feature.zero_crossing_rate(y)))
|
| 120 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
+
# MFCC 계산 (파라미터 조정)
|
| 123 |
+
mfccs = librosa.feature.mfcc(
|
| 124 |
+
y=y,
|
| 125 |
+
sr=sr,
|
| 126 |
+
n_mfcc=13,
|
| 127 |
+
n_mels=N_MELS
|
| 128 |
+
)
|
| 129 |
+
features["mfcc_mean"] = np.mean(mfccs, axis=1).tolist()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
return (
|
| 132 |
+
"음성이 성공적으로 분석되었습니다.", # 텍스트 출력
|
| 133 |
+
f"에너지: {features['energy']:.2f}\n템포: {features['tempo']:.2f}", # 감정 출력
|
| 134 |
+
features, # JSON 출력
|
| 135 |
+
state_data # 상태 업데이트
|
|
|
|
| 136 |
)
|
| 137 |
+
|
| 138 |
except Exception as e:
|
| 139 |
+
print(f"Error in analyze_voice: {str(e)}")
|
| 140 |
+
return f"오류 발생: {str(e)}", None, None, state_data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
# 이벤트 연결
|
| 143 |
+
start_btn.click(
|
| 144 |
fn=start_journey,
|
| 145 |
+
inputs=[name_input],
|
| 146 |
+
outputs=[user_display, tabs]
|
| 147 |
)
|
| 148 |
+
|
| 149 |
+
save_btn.click(
|
| 150 |
fn=save_reflection,
|
| 151 |
inputs=[reflection_input, state],
|
| 152 |
outputs=[state, reflections_display]
|
| 153 |
)
|
| 154 |
+
|
| 155 |
voice_input.change(
|
| 156 |
fn=analyze_voice,
|
| 157 |
inputs=[voice_input, state],
|
| 158 |
+
outputs=[text_output, emotion_output, audio_features, state]
|
| 159 |
)
|
| 160 |
|
| 161 |
return app
|
| 162 |
|
| 163 |
+
# 앱 실행
|
| 164 |
if __name__ == "__main__":
|
| 165 |
+
demo = create_interface()
|
| 166 |
+
demo.launch()
|