haepada commited on
Commit
36c54bd
·
verified ·
1 Parent(s): 7eac455

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -73
app.py CHANGED
@@ -8,12 +8,40 @@ import requests
8
  import json
9
  import time
10
  import threading
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- # 데이터 저장을 위한 DB 클래스
13
  class SimpleDB:
14
  def __init__(self, file_path="wishes.json"):
15
  self.file_path = file_path
16
  self.wishes = self._load_wishes()
 
 
 
 
 
17
 
18
  def _load_wishes(self):
19
  try:
@@ -42,43 +70,34 @@ class SimpleDB:
42
  print(f"Error saving wish: {e}")
43
  return False
44
 
45
- # 환경변수 및 API 설정
46
- HF_API_TOKEN = os.getenv("roots")
47
  if not HF_API_TOKEN:
48
- raise ValueError("roots token not found in environment variables")
49
 
50
  API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
51
- headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
52
 
53
  # AI 모델 초기화
54
- speech_recognizer = pipeline(
55
- "automatic-speech-recognition",
56
- model="kresnik/wav2vec2-large-xlsr-korean"
57
- )
58
- text_analyzer = pipeline(
59
- "sentiment-analysis",
60
- model="nlptown/bert-base-multilingual-uncased-sentiment"
61
- )
62
-
63
- IMAGE_DISPLAY_TIME = 30
64
- WELCOME_MESSAGE = """
65
- # 디지털 굿판에 오신 것을 환영합니다
66
-
67
- 디지털 굿판은 현대 도시 속에서 잊혀진 전통 굿의 정수를 담아낸 **디지털 의례의 공간**입니다.
68
- 이곳에서는 사람들의 목소리와 감정을 통해 **영적 교감**을 나누고, **자연과 도시의 에너지가 연결**됩니다.
69
- 이제, 평온함과 치유의 여정을 시작해보세요.
70
- """
71
-
72
- WORLDVIEW_MESSAGE = """
73
- ## 굿판의 세계관 🌌
74
-
75
- 온천천의 물줄기는 신성한 금샘에서 시작됩니다. 금샘은 생명과 창조의 원천이며,
76
- 천상의 생명이 지상에서 숨을 틔우는 자리입니다. 도시의 소음 속에서도 신성한 생명력을 느껴보세요.
77
- 이곳에서 영적인 교감을 경험하며, 자연과 하나 되는 순간을 맞이해 보시기 바랍니다.
78
-
79
- 이 앱은 온천천의 사운드스케이프를 녹음하여 제작되었으며,
80
- 온천천 온천장역에서 장전역까지 걸으며 더 깊은 체험이 가능합니다.
81
- """
82
  def calculate_baseline_features(audio_data):
83
  """기준점 음성 특성 분석"""
84
  try:
@@ -90,6 +109,11 @@ def calculate_baseline_features(audio_data):
90
  print("Unsupported audio format")
91
  return None
92
 
 
 
 
 
 
93
  features = {
94
  "energy": float(np.mean(librosa.feature.rms(y=y))),
95
  "tempo": float(librosa.beat.tempo(y, sr=sr)[0]),
@@ -104,6 +128,21 @@ def calculate_baseline_features(audio_data):
104
 
105
  def map_acoustic_to_emotion(features, baseline_features=None):
106
  """음향학적 특성을 감정으로 매핑"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  energy_norm = min(features["energy"] * 100, 100)
108
  tempo_norm = min(features["tempo"] / 200, 1)
109
  pitch_norm = min(features["pitch"] * 2, 1)
@@ -121,6 +160,7 @@ def map_acoustic_to_emotion(features, baseline_features=None):
121
  "characteristics": []
122
  }
123
 
 
124
  if energy_norm > 70:
125
  if tempo_norm > 0.6:
126
  emotions["primary"] = "기쁨/열정"
@@ -178,22 +218,27 @@ def analyze_voice(audio_data, state):
178
  return state, "오디오 형식을 지원하지 않습니다.", "", "", ""
179
 
180
  # 음향학적 특성 분석
181
- acoustic_features = {
182
- "energy": float(np.mean(librosa.feature.rms(y=y))),
183
- "tempo": float(librosa.beat.tempo(y, sr=sr)[0]),
184
- "pitch": float(np.mean(librosa.feature.zero_crossing_rate(y))),
185
- "volume": float(np.mean(np.abs(y)))
186
- }
187
 
188
  # 음성 감정 분석
189
  voice_emotion = map_acoustic_to_emotion(acoustic_features, state.get("baseline_features"))
190
 
191
  # 음성 인식
192
- transcription = speech_recognizer(y, sampling_rate=sr)
193
- text = transcription["text"]
 
 
 
194
 
195
  # 텍스트 감정 분석
196
- text_sentiment = text_analyzer(text)[0]
 
 
 
 
 
197
 
198
  # 결과 포맷팅
199
  voice_result = (
@@ -207,8 +252,6 @@ def analyze_voice(audio_data, state):
207
  f"- 음성 크기: {voice_emotion['details']['voice_volume']}"
208
  )
209
 
210
- text_result = f"텍스트 감정 분석: {text_sentiment['label']} (점수: {text_sentiment['score']:.2f})"
211
-
212
  # 프롬프트 생성
213
  prompt = generate_detailed_prompt(text, voice_emotion, text_sentiment)
214
 
@@ -217,6 +260,7 @@ def analyze_voice(audio_data, state):
217
 
218
  return state, text, voice_result, text_result, prompt
219
  except Exception as e:
 
220
  return state, f"오류 발생: {str(e)}", "", "", ""
221
 
222
  def generate_detailed_prompt(text, emotions, text_sentiment):
@@ -248,12 +292,11 @@ def generate_detailed_prompt(text, emotions, text_sentiment):
248
 
249
  def generate_image_from_prompt(prompt):
250
  """이미지 생성 함수"""
251
- print(f"Generating image with prompt: {prompt}")
252
- try:
253
- if not prompt:
254
- print("No prompt provided")
255
- return None, None
256
 
 
257
  response = requests.post(
258
  API_URL,
259
  headers=headers,
@@ -268,10 +311,8 @@ def generate_image_from_prompt(prompt):
268
  )
269
 
270
  if response.status_code == 200:
271
- print("Image generated successfully")
272
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
273
  image_path = f"generated_images/{timestamp}.png"
274
- os.makedirs("generated_images", exist_ok=True)
275
  with open(image_path, "wb") as f:
276
  f.write(response.content)
277
  return response.content, image_path
@@ -286,11 +327,11 @@ def generate_image_from_prompt(prompt):
286
  def save_reflection(text, state):
287
  """감상 저장"""
288
  if not text.strip():
289
- return state, state.get("reflections", [])
290
 
291
  try:
292
  current_time = datetime.now().strftime("%H:%M:%S")
293
- sentiment = text_analyzer(text)[0]
294
  new_reflection = [current_time, text, f"{sentiment['label']} ({sentiment['score']:.2f})"]
295
 
296
  reflections = state.get("reflections", [])
@@ -302,18 +343,22 @@ def save_reflection(text, state):
302
  return state, []
303
 
304
  def create_interface():
 
305
  db = SimpleDB()
 
 
 
 
 
 
 
 
 
 
306
 
307
  with gr.Blocks(theme=gr.themes.Soft()) as app:
308
- state = gr.State({
309
- "user_name": "",
310
- "baseline_features": None,
311
- "reflections": [],
312
- "wish": None,
313
- "final_prompt": "",
314
- "image_path": None
315
- })
316
-
317
  header = gr.Markdown("# 디지털 굿판")
318
  user_display = gr.Markdown("")
319
 
@@ -331,8 +376,10 @@ def create_interface():
331
  gr.Markdown("""### 축원의 문장을 평온한 마음으로 읽어주세요""")
332
  gr.Markdown("'당신의 건강과 행복이 늘 가득하기를'")
333
  baseline_audio = gr.Audio(
334
- label="축원 문장 녹음하기",
335
- type="numpy"
 
 
336
  )
337
  set_baseline_btn = gr.Button("기준점 설정 완료")
338
  baseline_status = gr.Markdown("")
@@ -346,7 +393,8 @@ def create_interface():
346
  type="filepath",
347
  label="온천천의 소리",
348
  interactive=False,
349
- autoplay=False
 
350
  )
351
  with gr.Column():
352
  reflection_input = gr.Textbox(
@@ -357,9 +405,8 @@ def create_interface():
357
  reflections_display = gr.Dataframe(
358
  headers=["시간", "감상", "감정 분석"],
359
  label="기록된 감상들",
360
- datatype=["str", "str", "str"],
361
- row_count=(0, "dynamic"),
362
- col_count=(3, "fixed")
363
  )
364
 
365
  with gr.Tab("기원"):
@@ -368,7 +415,9 @@ def create_interface():
368
  with gr.Column():
369
  voice_input = gr.Audio(
370
  label="소원을 나누고 싶은 마음을 말해주세요",
371
- type="numpy"
 
 
372
  )
373
  clear_btn = gr.Button("녹음 지우기")
374
  analyze_btn = gr.Button("소원 분석하기")
@@ -400,7 +449,7 @@ def create_interface():
400
  start_btn.click(
401
  fn=lambda name, state: (
402
  WORLDVIEW_MESSAGE if name.strip() else "이름을 입력해주세요",
403
- gr.update(visible=True) if name.strip() else gr.update(),
404
  {**state, "user_name": name} if name.strip() else state
405
  ),
406
  inputs=[name_input, state],
@@ -420,7 +469,7 @@ def create_interface():
420
  )
421
 
422
  clear_btn.click(
423
- fn=lambda: None,
424
  outputs=[voice_input]
425
  )
426
 
@@ -452,7 +501,13 @@ def create_interface():
452
 
453
  return app
454
 
455
- # 파일 맨 아래 부분
456
  if __name__ == "__main__":
457
  demo = create_interface()
458
- demo.launch(debug=True, share=True)
 
 
 
 
 
 
 
 
8
  import json
9
  import time
10
  import threading
11
+ from dotenv import load_dotenv
12
+
13
+ # 환경변수 로드
14
+ load_dotenv()
15
+
16
+ # 상수 정의
17
+ WELCOME_MESSAGE = """
18
+ # 디지털 굿판에 오신 것을 환영합니다
19
+
20
+ 디지털 굿판은 현대 도시 속에서 잊혀진 전통 굿의 정수를 담아낸 **디지털 의례의 공간**입니다.
21
+ 이곳에서는 사람들의 목소리와 감정을 통해 **영적 교감**을 나누고, **자연과 도시의 에너지가 연결**됩니다.
22
+ 이제, 평온함과 치유의 여정을 시작해보세요.
23
+ """
24
+
25
+ WORLDVIEW_MESSAGE = """
26
+ ## 굿판의 세계관 🌌
27
+
28
+ 온천천의 물줄기는 신성한 금샘에서 시작됩니다. 금샘은 생명과 창조의 원천이며,
29
+ 천상의 생명이 지상에서 숨을 틔우는 자리입니다. 도시의 소음 속에서도 신성한 생명력을 느껴보세요.
30
+ 이곳에서 영적인 교감을 경험하며, 자연과 하나 되는 순간을 맞이해 보시기 바랍니다.
31
+
32
+ 이 앱은 온천천의 사운드스케이프를 녹음하여 제작되었으며,
33
+ 온천천 온천장역에서 장전역까지 걸으며 더 깊은 체험이 가능합니다.
34
+ """
35
 
 
36
  class SimpleDB:
37
  def __init__(self, file_path="wishes.json"):
38
  self.file_path = file_path
39
  self.wishes = self._load_wishes()
40
+
41
+ # wishes.json 파일이 없으면 생성
42
+ if not os.path.exists(self.file_path):
43
+ with open(self.file_path, 'w', encoding='utf-8') as f:
44
+ json.dump([], f, ensure_ascii=False, indent=2)
45
 
46
  def _load_wishes(self):
47
  try:
 
70
  print(f"Error saving wish: {e}")
71
  return False
72
 
73
+ # API 설정
74
+ HF_API_TOKEN = os.getenv("roots", "") # 기본값을 빈 문자열로 설정
75
  if not HF_API_TOKEN:
76
+ print("Warning: HuggingFace API token not found. Some features may be limited.")
77
 
78
  API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
79
+ headers = {"Authorization": f"Bearer {HF_API_TOKEN}"} if HF_API_TOKEN else {}
80
 
81
  # AI 모델 초기화
82
+ try:
83
+ speech_recognizer = pipeline(
84
+ "automatic-speech-recognition",
85
+ model="kresnik/wav2vec2-large-xlsr-korean"
86
+ )
87
+ text_analyzer = pipeline(
88
+ "sentiment-analysis",
89
+ model="nlptown/bert-base-multilingual-uncased-sentiment"
90
+ )
91
+ except Exception as e:
92
+ print(f"Error initializing AI models: {e}")
93
+ # 기본 파이프라인 설정
94
+ speech_recognizer = None
95
+ text_analyzer = None
96
+
97
+ # 필요한 디렉토리 생성
98
+ os.makedirs("generated_images", exist_ok=True)
99
+
100
+ # 음성 분석 관련 함수들
 
 
 
 
 
 
 
 
 
101
  def calculate_baseline_features(audio_data):
102
  """기준점 음성 특성 분석"""
103
  try:
 
109
  print("Unsupported audio format")
110
  return None
111
 
112
+ # 음성이 없는 경우 처리
113
+ if len(y) == 0:
114
+ print("Empty audio data")
115
+ return None
116
+
117
  features = {
118
  "energy": float(np.mean(librosa.feature.rms(y=y))),
119
  "tempo": float(librosa.beat.tempo(y, sr=sr)[0]),
 
128
 
129
  def map_acoustic_to_emotion(features, baseline_features=None):
130
  """음향학적 특성을 감정으로 매핑"""
131
+ if features is None:
132
+ return {
133
+ "primary": "알 수 없음",
134
+ "intensity": 0,
135
+ "confidence": 0.0,
136
+ "secondary": "",
137
+ "characteristics": ["음성 분석 실패"],
138
+ "details": {
139
+ "energy_level": "0%",
140
+ "speech_rate": "알 수 없음",
141
+ "pitch_variation": "알 수 없음",
142
+ "voice_volume": "알 수 없음"
143
+ }
144
+ }
145
+
146
  energy_norm = min(features["energy"] * 100, 100)
147
  tempo_norm = min(features["tempo"] / 200, 1)
148
  pitch_norm = min(features["pitch"] * 2, 1)
 
160
  "characteristics": []
161
  }
162
 
163
+ # 감정 매핑 로직
164
  if energy_norm > 70:
165
  if tempo_norm > 0.6:
166
  emotions["primary"] = "기쁨/열정"
 
218
  return state, "오디오 형식을 지원하지 않습니다.", "", "", ""
219
 
220
  # 음향학적 특성 분석
221
+ acoustic_features = calculate_baseline_features(audio_data)
222
+ if acoustic_features is None:
223
+ return state, "음성 분석에 실패했습니다.", "", "", ""
 
 
 
224
 
225
  # 음성 감정 분석
226
  voice_emotion = map_acoustic_to_emotion(acoustic_features, state.get("baseline_features"))
227
 
228
  # 음성 인식
229
+ if speech_recognizer:
230
+ transcription = speech_recognizer({"sampling_rate": sr, "raw": y})
231
+ text = transcription["text"]
232
+ else:
233
+ text = "음성 인식 모델을 불러올 수 없습니다."
234
 
235
  # 텍스트 감정 분석
236
+ if text_analyzer and text:
237
+ text_sentiment = text_analyzer(text)[0]
238
+ text_result = f"텍스트 감정 분석: {text_sentiment['label']} (점수: {text_sentiment['score']:.2f})"
239
+ else:
240
+ text_sentiment = {"label": "unknown", "score": 0.0}
241
+ text_result = "텍스트 감정 분석을 수행할 수 없습니다."
242
 
243
  # 결과 포맷팅
244
  voice_result = (
 
252
  f"- 음성 크기: {voice_emotion['details']['voice_volume']}"
253
  )
254
 
 
 
255
  # 프롬프트 생성
256
  prompt = generate_detailed_prompt(text, voice_emotion, text_sentiment)
257
 
 
260
 
261
  return state, text, voice_result, text_result, prompt
262
  except Exception as e:
263
+ print(f"Error in analyze_voice: {str(e)}")
264
  return state, f"오류 발생: {str(e)}", "", "", ""
265
 
266
  def generate_detailed_prompt(text, emotions, text_sentiment):
 
292
 
293
  def generate_image_from_prompt(prompt):
294
  """이미지 생성 함수"""
295
+ if not prompt:
296
+ print("No prompt provided")
297
+ return None, None
 
 
298
 
299
+ try:
300
  response = requests.post(
301
  API_URL,
302
  headers=headers,
 
311
  )
312
 
313
  if response.status_code == 200:
 
314
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
315
  image_path = f"generated_images/{timestamp}.png"
 
316
  with open(image_path, "wb") as f:
317
  f.write(response.content)
318
  return response.content, image_path
 
327
  def save_reflection(text, state):
328
  """감상 저장"""
329
  if not text.strip():
330
+ return state, []
331
 
332
  try:
333
  current_time = datetime.now().strftime("%H:%M:%S")
334
+ sentiment = text_analyzer(text)[0] if text_analyzer else {"label": "unknown", "score": 0.0}
335
  new_reflection = [current_time, text, f"{sentiment['label']} ({sentiment['score']:.2f})"]
336
 
337
  reflections = state.get("reflections", [])
 
343
  return state, []
344
 
345
  def create_interface():
346
+ """Gradio 인터페이스 생성"""
347
  db = SimpleDB()
348
+
349
+ # 초기 상태값 설정
350
+ initial_state = {
351
+ "user_name": "",
352
+ "baseline_features": None,
353
+ "reflections": [],
354
+ "wish": None,
355
+ "final_prompt": "",
356
+ "image_path": None
357
+ }
358
 
359
  with gr.Blocks(theme=gr.themes.Soft()) as app:
360
+ state = gr.State(value=initial_state)
361
+
 
 
 
 
 
 
 
362
  header = gr.Markdown("# 디지털 굿판")
363
  user_display = gr.Markdown("")
364
 
 
376
  gr.Markdown("""### 축원의 문장을 평온한 마음으로 읽어주세요""")
377
  gr.Markdown("'당신의 건강과 행복이 늘 가득하기를'")
378
  baseline_audio = gr.Audio(
379
+ label="축원 문장 녹음하기",
380
+ type="numpy",
381
+ source="microphone",
382
+ streaming=False
383
  )
384
  set_baseline_btn = gr.Button("기준점 설정 완료")
385
  baseline_status = gr.Markdown("")
 
393
  type="filepath",
394
  label="온천천의 소리",
395
  interactive=False,
396
+ autoplay=False,
397
+ visible=True
398
  )
399
  with gr.Column():
400
  reflection_input = gr.Textbox(
 
405
  reflections_display = gr.Dataframe(
406
  headers=["시간", "감상", "감정 분석"],
407
  label="기록된 감상들",
408
+ value=[[]],
409
+ interactive=False
 
410
  )
411
 
412
  with gr.Tab("기원"):
 
415
  with gr.Column():
416
  voice_input = gr.Audio(
417
  label="소원을 나누고 싶은 마음을 말해주세요",
418
+ type="numpy",
419
+ source="microphone",
420
+ streaming=False
421
  )
422
  clear_btn = gr.Button("녹음 지우기")
423
  analyze_btn = gr.Button("소원 분석하기")
 
449
  start_btn.click(
450
  fn=lambda name, state: (
451
  WORLDVIEW_MESSAGE if name.strip() else "이름을 입력해주세요",
452
+ gr.update(visible=True) if name.strip() else gr.update(visible=False),
453
  {**state, "user_name": name} if name.strip() else state
454
  ),
455
  inputs=[name_input, state],
 
469
  )
470
 
471
  clear_btn.click(
472
+ fn=lambda: gr.update(value=None),
473
  outputs=[voice_input]
474
  )
475
 
 
501
 
502
  return app
503
 
 
504
  if __name__ == "__main__":
505
  demo = create_interface()
506
+ demo.launch(
507
+ debug=True,
508
+ share=True,
509
+ show_error=True,
510
+ server_name="0.0.0.0",
511
+ server_port=7860
512
+ )
513
+