haepada commited on
Commit
9d47e7f
·
verified ·
1 Parent(s): db42dba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -176
app.py CHANGED
@@ -5,219 +5,162 @@ from transformers import pipeline
5
  from datetime import datetime
6
  import os
7
 
 
 
 
 
8
  # AI 모델 초기화
9
- speech_recognizer = pipeline("automatic-speech-recognition",
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
- "voice_analyses": [],
24
- "current_prompt": "",
25
- "generated_images": []
26
  })
27
 
28
- with gr.Column():
29
- # 사용자 이름 표시
30
- user_name_display = gr.Markdown("", elem_id="user-name-display")
31
-
32
- # 단계별
33
- with gr.Tabs() as tabs:
34
- # 1. 입장
35
- with gr.Tab("입장", id="intro"):
36
- gr.Markdown("""
37
- # 디지털 굿판에 오신 것을 환영합니다
38
- 온천천의 디지털 치유 공간으로 들어가보세요.
39
- """)
40
- name_input = gr.Textbox(label="이름을 알려주세요")
41
- start_button = gr.Button("여정 시작하기")
42
-
43
- # 2. 청신
44
- with gr.Tab("청신", id="cleansing"):
45
- gr.Markdown("## 청신 - 소리로 정화하기")
46
- with gr.Row():
47
- # 음악 플레이어
48
- audio_player = gr.Audio(
49
- value=os.path.join(os.path.dirname(__file__), "assets", "main_music.mp3"),
50
- type="filepath",
51
- label="온천천의 소리",
52
- interactive=True,
53
- autoplay=True
 
 
 
54
  )
55
-
56
- # 감상 입력
57
- with gr.Column():
58
- reflection_input = gr.Textbox(
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
- # 4. 송신
95
- with gr.Tab("송신", id="sharing"):
96
- gr.Markdown("## 송신 - 함께 나누기")
97
- with gr.Row():
98
- # 프롬프트 이미지 표시
99
- final_prompt = gr.Textbox(
100
- label="생성된 프롬프트",
101
- interactive=False
102
- )
103
- generated_gallery = gr.Gallery(
104
- label="시각화 결과",
105
- columns=2,
106
- height="auto"
107
- )
 
 
 
 
108
 
109
  # 함수 정의
110
- def start_journey(name, state):
111
- """여정 시작 함수"""
112
- state["user_name"] = name
113
- return (
114
- state,
115
- f"# 환영합니다, {name}님",
116
- gr.update(selected="cleansing")
117
- )
118
-
119
- def analyze_voice(audio_path, state):
120
- """종합적인 음성 분석 함수"""
 
121
  try:
122
- if audio_path is None:
123
- return state, {"error": "음성 입력이 없습니다."}, "", ""
124
-
125
- # 오디오 로드
126
- y, sr = librosa.load(audio_path)
 
 
 
 
 
 
 
127
 
128
- # 1. 음향학적 특성 분석
129
- acoustic_features = {
 
 
 
 
 
 
 
 
 
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
- # 4. 텍스트 감정 분석
144
- text_sentiment = text_analyzer(text_result["text"])[0]
145
-
146
- # 결과 종합
147
- analysis_result = {
148
- "acoustic_analysis": acoustic_features,
149
- "voice_emotion": emotion_result[0],
150
- "text": text_result["text"],
151
- "text_sentiment": text_sentiment
152
- }
153
-
154
- # 프롬프트 생성
155
- prompt = generate_art_prompt(analysis_result)
156
- state["current_prompt"] = prompt
157
 
158
  return (
159
- state,
160
- analysis_result,
161
- text_result["text"],
162
- f"음성 감정: {emotion_result[0]['label']} ({emotion_result[0]['score']:.2f})\n"
163
- f"텍스트 감정: {text_sentiment['label']} ({text_sentiment['score']:.2f})"
164
  )
165
-
166
  except Exception as e:
167
- return state, {"error": str(e)}, "", ""
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
- start_button.click(
202
  fn=start_journey,
203
- inputs=[name_input, state],
204
- outputs=[state, user_name_display, tabs]
205
  )
206
-
207
- save_reflection.click(
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=[state, analysis_output, text_output, emotion_output]
217
  )
218
 
219
  return app
220
 
 
221
  if __name__ == "__main__":
222
- interface = create_interface()
223
- interface.launch()
 
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()