haepada commited on
Commit
8ae9c3e
·
verified ·
1 Parent(s): 0acbc79

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -162
app.py CHANGED
@@ -1,5 +1,4 @@
1
-
2
- # Part 1/4 - Imports and Initial Setup
3
  import gradio as gr
4
  import numpy as np
5
  import librosa
@@ -9,6 +8,7 @@ import os
9
  import requests
10
  import json
11
  import time
 
12
 
13
  # 데이터 저장을 위한 DB 클래스
14
  class SimpleDB:
@@ -61,7 +61,6 @@ text_analyzer = pipeline(
61
  model="nlptown/bert-base-multilingual-uncased-sentiment"
62
  )
63
 
64
- # 상수 정의
65
  IMAGE_DISPLAY_TIME = 30
66
  WELCOME_MESSAGE = """
67
  # 디지털 굿판에 오신 것을 환영합니다
@@ -82,8 +81,6 @@ WORLDVIEW_MESSAGE = """
82
  온천천 온천장역에서 장전역까지 걸으며 더 깊은 체험이 가능합니다.
83
  """
84
 
85
-
86
- # Part 2/4 - Analysis Functions
87
  def calculate_baseline_features(audio_path):
88
  """기준점 음성 특성 분석"""
89
  try:
@@ -208,8 +205,6 @@ def analyze_voice(audio_path, state):
208
  except Exception as e:
209
  return state, f"오류 발생: {str(e)}", "", "", ""
210
 
211
-
212
- # Part 3/4 - Generation and Processing Functions
213
  def generate_detailed_prompt(text, emotions, text_sentiment):
214
  """감정 기반 상세 프롬프트 생성"""
215
  emotion_colors = {
@@ -260,7 +255,6 @@ def generate_image_from_prompt(prompt):
260
 
261
  if response.status_code == 200:
262
  print("Image generated successfully")
263
- # 이미지 저장
264
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
265
  image_path = f"generated_images/{timestamp}.png"
266
  os.makedirs("generated_images", exist_ok=True)
@@ -275,24 +269,10 @@ def generate_image_from_prompt(prompt):
275
  print(f"Error generating image: {str(e)}")
276
  return None, None
277
 
278
- def update_final_prompt(state):
279
- """청신의 감상들을 종합하여 최종 프롬프트 업데이트"""
280
- combined_prompt = "한국 전통 민화 스타일의 추상화, 온천천에서의 감상과 소원을 담아내기:\n\n"
281
-
282
- if state.get("reflections"):
283
- combined_prompt += "청신의 감상들:\n"
284
- for time, text, sentiment in state["reflections"]:
285
- combined_prompt += f"- {time}: {text} ({sentiment})\n"
286
-
287
- if state.get("wish"):
288
- combined_prompt += f"\n소원:\n{state['wish']}"
289
-
290
- return combined_prompt
291
-
292
- def handle_image_timeout(result_image, delay=IMAGE_DISPLAY_TIME):
293
- """이미지 자동 사라짐 처리"""
294
- time.sleep(delay)
295
- return gr.update(value=None)
296
 
297
  def save_reflection(text, state):
298
  """감상 저장"""
@@ -313,8 +293,6 @@ def save_reflection(text, state):
313
  print(f"Error in save_reflection: {str(e)}")
314
  return state, []
315
 
316
-
317
- # Part 4/4 - Interface and Main
318
  def create_interface():
319
  db = SimpleDB()
320
 
@@ -328,12 +306,10 @@ def create_interface():
328
  "image_path": None
329
  })
330
 
331
- # 헤더
332
  header = gr.Markdown("# 디지털 굿판")
333
  user_display = gr.Markdown("")
334
 
335
  with gr.Tabs() as tabs:
336
- # 입장
337
  with gr.Tab("입장"):
338
  gr.Markdown(WELCOME_MESSAGE)
339
  name_input = gr.Textbox(
@@ -343,139 +319,133 @@ def create_interface():
343
  worldview_display = gr.Markdown(visible=False)
344
  start_btn = gr.Button("여정 시작하기")
345
 
346
- # 기준 설정
347
  with gr.Tab("기준 설정"):
348
- gr.Markdown("""### 축원의 문장을 평온한 마음으로 읽어주세요
349
-
350
- 먼저, 평온한 마음으로 축원의 문장을 읽어주세요.
351
- 이 축원은 당신에게 평화와 안정을 불러일으키며,
352
- 감정을 정확히 이해하기 위한 **기준점**이 될 것입니다.""")
353
  gr.Markdown("'당신의 건강과 행복이 늘 가득하기를'")
354
- baseline_audio = gr.Audio(
355
- label="축원 문장 녹음하기",
356
- sources=["microphone"]
357
- )
358
- set_baseline_btn = gr.Button("기준점 설정 완료")
359
- baseline_status = gr.Markdown("")
360
-
361
- # 청신
362
- with gr.Tab("청신"):
363
- gr.Markdown("""## 청신 - 소리로 정화하기
364
-
365
- 온천천의 물소리에 귀 기울이며 **30분간 마음을 정화**해보세요.""")
366
- play_music_btn = gr.Button("온천천의 소리 듣기")
367
- with gr.Row():
368
- audio = gr.Audio(
369
- value=None,
370
- type="filepath",
371
- label="온천천의 소리",
372
- interactive=False,
373
- autoplay=False
374
- )
375
- with gr.Column():
376
- reflection_input = gr.Textbox(
377
- label="지금 이 순간의 감상을 자유롭게 적어보세요",
378
- lines=3
379
- )
380
- save_btn = gr.Button("감상 저장하기")
381
- reflections_display = gr.Dataframe(
382
- headers=["시간", "감상", "감정 분석"],
383
- label="기록된 감상들"
384
- )
385
-
386
- # 기원
387
- with gr.Tab("기원"):
388
- gr.Markdown("## 기원 - 소원을 전해보세요")
389
- with gr.Row():
390
- with gr.Column():
391
- voice_input = gr.Audio(
392
- label="소원을 나누고 싶은 마음을 말해주세요",
393
- sources=["microphone"]
394
- )
395
- clear_btn = gr.Button("녹음 지우기")
396
- analyze_btn = gr.Button("소원 분석하기")
397
-
398
- with gr.Column():
399
- transcribed_text = gr.Textbox(label="인식된 텍스트")
400
- voice_emotion = gr.Textbox(label="음성 감정 분석")
401
- text_emotion = gr.Textbox(label="텍스트 감정 분석")
402
-
403
- # 송신
404
- with gr.Tab("송신"):
405
- gr.Markdown("## 송신 - 마음의 그림을 남기고, 보내기")
406
- final_prompt = gr.Textbox(
407
- label="생성된 프롬프트",
408
- interactive=False,
409
- lines=3
410
- )
411
- with gr.Row():
412
- generate_btn = gr.Button("마음의 그림 그리기")
413
- save_image_btn = gr.Button("이미지 저장하기")
414
- result_image = gr.Image(label="생성된 이미지")
415
-
416
- gr.Markdown("## 마지막 감상을 남겨주세요")
417
- final_reflection = gr.Textbox(
418
- label="마지막 감상",
419
- placeholder="한 줄로 남겨주세요..."
420
- )
421
- save_final_btn = gr.Button("감상 남기기")
422
-
423
- # 이벤트 연결
424
- start_btn.click(
425
- fn=lambda name: (
426
- WORLDVIEW_MESSAGE if name.strip() else "이름을 입력해주세요",
427
- gr.update(visible=True) if name.strip() else gr.update(),
428
- {"user_name": name} if name.strip() else state
429
- ),
430
- inputs=[name_input],
431
- outputs=[worldview_display, tabs, state]
432
- )
433
-
434
- set_baseline_btn.click(
435
- fn=lambda x, s: ({"baseline_features": calculate_baseline_features(x)}, "기준점이 설정되었습니다."),
436
- inputs=[baseline_audio, state],
437
- outputs=[state, baseline_status]
438
- )
439
-
440
- save_btn.click(
441
- fn=save_reflection,
442
- inputs=[reflection_input, state],
443
- outputs=[state, reflections_display]
444
- )
445
-
446
- clear_btn.click(
447
- fn=lambda: None,
448
- outputs=[voice_input]
449
- )
450
-
451
- analyze_btn.click(
452
- fn=analyze_voice,
453
- inputs=[voice_input, state],
454
- outputs=[state, transcribed_text, voice_emotion, text_emotion, final_prompt]
455
- )
456
-
457
- generate_btn.click(
458
- fn=lambda p: generate_image_from_prompt(p)[0],
459
- inputs=[final_prompt],
460
- outputs=[result_image]
461
- )
462
-
463
- save_final_btn.click(
464
- fn=lambda t, s: (db.save_wish(s["user_name"], t), "감상이 저장되었습니다."),
465
- inputs=[final_reflection, state],
466
- outputs=[gr.Markdown("")]
467
- )
468
-
469
- # 이미지 자동 사라짐
470
- result_image.change(
471
- fn=lambda: gr.update(value=None),
472
- inputs=[],
473
- outputs=[result_image],
474
- _js=f"() => setTimeout(() => {{document.querySelector('#result_image image').src = ''}}, {IMAGE_DISPLAY_TIME*1000})"
475
- )
476
-
477
- return app
478
 
479
  if __name__ == "__main__":
480
- demo = create_interface()
481
- demo.launch(debug=True)
 
 
1
+ ```python
 
2
  import gradio as gr
3
  import numpy as np
4
  import librosa
 
8
  import requests
9
  import json
10
  import time
11
+ import threading
12
 
13
  # 데이터 저장을 위한 DB 클래스
14
  class SimpleDB:
 
61
  model="nlptown/bert-base-multilingual-uncased-sentiment"
62
  )
63
 
 
64
  IMAGE_DISPLAY_TIME = 30
65
  WELCOME_MESSAGE = """
66
  # 디지털 굿판에 오신 것을 환영합니다
 
81
  온천천 온천장역에서 장전역까지 걸으며 더 깊은 체험이 가능합니다.
82
  """
83
 
 
 
84
  def calculate_baseline_features(audio_path):
85
  """기준점 음성 특성 분석"""
86
  try:
 
205
  except Exception as e:
206
  return state, f"오류 발생: {str(e)}", "", "", ""
207
 
 
 
208
  def generate_detailed_prompt(text, emotions, text_sentiment):
209
  """감정 기반 상세 프롬프트 생성"""
210
  emotion_colors = {
 
255
 
256
  if response.status_code == 200:
257
  print("Image generated successfully")
 
258
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
259
  image_path = f"generated_images/{timestamp}.png"
260
  os.makedirs("generated_images", exist_ok=True)
 
269
  print(f"Error generating image: {str(e)}")
270
  return None, None
271
 
272
+ def handle_image_timeout(result_image):
273
+ """이미지 자동 사라짐을 처리하는 함수"""
274
+ time.sleep(IMAGE_DISPLAY_TIME)
275
+ result_image.update(value=None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
 
277
  def save_reflection(text, state):
278
  """감상 저장"""
 
293
  print(f"Error in save_reflection: {str(e)}")
294
  return state, []
295
 
 
 
296
  def create_interface():
297
  db = SimpleDB()
298
 
 
306
  "image_path": None
307
  })
308
 
 
309
  header = gr.Markdown("# 디지털 굿판")
310
  user_display = gr.Markdown("")
311
 
312
  with gr.Tabs() as tabs:
 
313
  with gr.Tab("입장"):
314
  gr.Markdown(WELCOME_MESSAGE)
315
  name_input = gr.Textbox(
 
319
  worldview_display = gr.Markdown(visible=False)
320
  start_btn = gr.Button("여정 시작하기")
321
 
 
322
  with gr.Tab("기준 설정"):
323
+ gr.Markdown("""### 축원의 문장을 평온한 마음으로 읽어주세요""")
 
 
 
 
324
  gr.Markdown("'당신의 건강과 행복이 늘 가득하기를'")
325
+ baseline_audio = gr.Audio(
326
+ label="축원 문장 녹음하기",
327
+ sources=["microphone"]
328
+ )
329
+ set_baseline_btn = gr.Button("기준점 설정 완료")
330
+ baseline_status = gr.Markdown("")
331
+
332
+ with gr.Tab("청신"):
333
+ gr.Markdown("## 청신 - 소리로 정화하기")
334
+ play_music_btn = gr.Button("온천천의 소리 듣기")
335
+ with gr.Row():
336
+ audio = gr.Audio(
337
+ value=None,
338
+ type="filepath",
339
+ label="온천천의 소리",
340
+ interactive=False,
341
+ autoplay=False
342
+ )
343
+ with gr.Column():
344
+ reflection_input = gr.Textbox(
345
+ label="지금 이 순간의 감상을 자유롭게 적어보세요",
346
+ lines=3
347
+ )
348
+ save_btn = gr.Button("감상 저장하기")
349
+ reflections_display = gr.Dataframe(
350
+ headers=["시간", "감상", "감정 분석"],
351
+ label="기록된 감상들"
352
+ )
353
+
354
+ with gr.Tab("기원"):
355
+ gr.Markdown("## 기원 - 소원을 전해보세요")
356
+ with gr.Row():
357
+ with gr.Column():
358
+ voice_input = gr.Audio(
359
+ label="소원을 나누고 싶은 마음을 말해주세요",
360
+ sources=["microphone"]
361
+ )
362
+ clear_btn = gr.Button("녹음 지우기")
363
+ analyze_btn = gr.Button("소원 분석하기")
364
+
365
+ with gr.Column():
366
+ transcribed_text = gr.Textbox(label="인식된 텍스트")
367
+ voice_emotion = gr.Textbox(label="음성 감정 분석")
368
+ text_emotion = gr.Textbox(label="텍스트 감정 분석")
369
+
370
+ with gr.Tab("송신"):
371
+ gr.Markdown("## 송신 - 마음의 그림을 남기고, 보내기")
372
+ final_prompt = gr.Textbox(
373
+ label="생성된 프롬프트",
374
+ interactive=False,
375
+ lines=3
376
+ )
377
+ generate_btn = gr.Button("마음의 그림 그리기")
378
+ result_image = gr.Image(label="생성된 이미지")
379
+
380
+ gr.Markdown("## 마지막 감상을 남겨주세요")
381
+ final_reflection = gr.Textbox(
382
+ label="마지막 감상",
383
+ placeholder=" 줄로 남겨주세요..."
384
+ )
385
+ save_final_btn = gr.Button("감상 남기기")
386
+
387
+ def delayed_image_clear():
388
+ time.sleep(IMAGE_DISPLAY_TIME)
389
+ return gr.update(value=None)
390
+
391
+ def on_image_generated(prompt):
392
+ image_content = generate_image_from_prompt(prompt)
393
+ if image_content:
394
+ # Start a timer to clear the image
395
+ timer = threading.Timer(IMAGE_DISPLAY_TIME, lambda: result_image.update(value=None))
396
+ timer.start()
397
+ return image_content
398
+ return None
399
+
400
+ # 이벤트 연결
401
+ start_btn.click(
402
+ fn=lambda name: (
403
+ WORLDVIEW_MESSAGE if name.strip() else "이름을 입력해주세요",
404
+ gr.update(visible=True) if name.strip() else gr.update(),
405
+ {"user_name": name} if name.strip() else state
406
+ ),
407
+ inputs=[name_input],
408
+ outputs=[worldview_display, tabs, state]
409
+ )
410
+
411
+ set_baseline_btn.click(
412
+ fn=lambda x, s: ({"baseline_features": calculate_baseline_features(x)}, "기준점이 설정되었습니다."),
413
+ inputs=[baseline_audio, state],
414
+ outputs=[state, baseline_status]
415
+ )
416
+
417
+ save_btn.click(
418
+ fn=save_reflection,
419
+ inputs=[reflection_input, state],
420
+ outputs=[state, reflections_display]
421
+ )
422
+
423
+ clear_btn.click(
424
+ fn=lambda: None,
425
+ outputs=[voice_input]
426
+ )
427
+
428
+ analyze_btn.click(
429
+ fn=analyze_voice,
430
+ inputs=[voice_input, state],
431
+ outputs=[state, transcribed_text, voice_emotion, text_emotion, final_prompt]
432
+ )
433
+
434
+ generate_btn.click(
435
+ fn=on_image_generated,
436
+ inputs=[final_prompt],
437
+ outputs=[result_image]
438
+ )
439
+
440
+ save_final_btn.click(
441
+ fn=lambda t, s: (db.save_wish(s["user_name"], t), "감상이 저장되었습니다."),
442
+ inputs=[final_reflection, state],
443
+ outputs=[gr.Markdown("")]
444
+ )
445
+
446
+ return app
 
 
447
 
448
  if __name__ == "__main__":
449
+ demo = create_interface()
450
+ demo.launch(debug=True)
451
+