File size: 36,299 Bytes
dddc22b
 
bb63470
 
33cb0be
dddc22b
 
8b6ea6c
b7baa07
36c54bd
 
 
 
 
b7baa07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36c54bd
 
 
 
5156ec3
 
36c54bd
 
2f16de0
b7baa07
36c54bd
b7baa07
 
36c54bd
b7baa07
 
e006b08
b7baa07
 
dddc22b
b7baa07
 
dddc22b
b7baa07
 
 
 
 
 
 
 
 
 
 
dddc22b
33cb0be
bed0080
 
33cb0be
bed0080
 
33cb0be
 
 
 
 
 
 
 
 
 
 
 
6000375
bed0080
 
 
33cb0be
bed0080
33cb0be
 
 
 
bed0080
 
33cb0be
 
bed0080
 
 
33cb0be
 
 
bed0080
 
33cb0be
 
 
 
 
 
 
 
 
 
 
 
 
 
bed0080
 
33cb0be
 
b7baa07
36c54bd
158bfd0
0acbc79
158bfd0
 
d7b7fbe
158bfd0
 
 
 
 
 
36c54bd
 
 
 
0acbc79
 
d7b7fbe
eefb51e
0acbc79
 
 
 
 
 
 
 
 
36c54bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0acbc79
 
 
 
 
2f16de0
eefb51e
 
 
0acbc79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158bfd0
 
0acbc79
158bfd0
0acbc79
6f76a92
 
 
 
 
 
 
 
2f16de0
158bfd0
6f76a92
b7baa07
36c54bd
4991658
 
 
 
 
6f76a92
 
 
 
 
 
b7baa07
 
6f76a92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158bfd0
0acbc79
6f76a92
158bfd0
 
6f76a92
4991658
0acbc79
36c54bd
6f76a92
0acbc79
33cb0be
 
 
 
 
 
 
 
 
 
 
 
57c75c6
 
 
 
 
 
 
 
 
 
 
b7baa07
 
 
 
 
 
 
 
 
33cb0be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dddc22b
b7baa07
33cb0be
b7baa07
 
4709eba
b7baa07
 
 
 
 
 
 
 
 
 
 
 
 
4709eba
b7baa07
 
03598da
b7baa07
 
 
 
541e490
03598da
 
 
541e490
 
 
 
b7baa07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34cd2ff
b7baa07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4709eba
b7baa07
 
 
bc3c19e
b7baa07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34cd2ff
b7baa07
 
 
 
 
 
34cd2ff
b7baa07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01c0d7d
b7baa07
 
 
4a1861f
b7baa07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33cb0be
b7baa07
 
 
 
34cd2ff
b7baa07
 
3010d56
b7baa07
2aa50fa
b7baa07
1089706
b7baa07
1089706
b7baa07
 
 
1089706
2b97308
 
 
 
 
 
 
1089706
5156ec3
6ee33cd
2b97308
 
 
 
5156ec3
1089706
2b97308
 
 
 
 
567bf65
2b97308
 
6f76a92
 
 
 
567bf65
 
 
 
4a1861f
567bf65
 
 
 
 
2b97308
 
 
 
 
 
 
 
 
 
 
b7baa07
2b97308
 
 
 
 
 
 
 
541e490
b7baa07
 
541e490
 
 
 
 
 
 
 
 
 
 
 
2b97308
541e490
 
1089706
2b97308
 
 
 
b7baa07
541e490
2b97308
 
 
 
 
 
34cd2ff
b7baa07
2b97308
 
 
 
34cd2ff
2b97308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7baa07
2b97308
 
 
 
 
 
 
 
b7baa07
 
 
2b97308
 
 
 
 
 
 
b7baa07
 
24a8312
03598da
24a8312
 
b7baa07
24a8312
01c0d7d
24a8312
 
 
 
 
 
01c0d7d
b7baa07
01c0d7d
24a8312
 
 
 
b7baa07
bed0080
b7baa07
22303ab
 
 
 
 
33cb0be
22303ab
 
 
 
bed0080
22303ab
 
 
b7baa07
22303ab
c9c9cb7
22303ab
 
 
 
a29bd41
22303ab
b7baa07
22303ab
 
 
2ff0e01
22303ab
 
 
 
0dfe358
22303ab
541e490
22303ab
34cd2ff
22303ab
33cb0be
22303ab
 
 
 
 
1089706
22303ab
 
 
b7baa07
22303ab
b7baa07
33cb0be
0dfe358
33cb0be
b7baa07
 
 
 
 
 
 
 
 
 
541e490
b7baa07
 
 
 
 
 
7c45562
b7baa07
 
 
 
 
 
 
 
 
 
 
 
541e490
7c45562
aa9026f
7c45562
 
 
 
 
 
 
b7baa07
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
import os
import json
import numpy as np
import librosa
from datetime import datetime
import gradio as gr
from transformers import pipeline
import requests
import base64
from dotenv import load_dotenv

# 환경변수 로드
load_dotenv()

# 필요한 디렉토리 생성
REQUIRED_DIRS = ['static', 'assets', 'data', 'generated_images', 'templates']
for directory in REQUIRED_DIRS:
    os.makedirs(directory, exist_ok=True)

# 필요한 파일 경로 정의
REQUIRED_FILES = {
    'static/main-image.png': '메인 이미지',
    'static/DIGITAL_GUTPAN_LOGO_m.png': '모바일 로고',
    'static/DIGITAL_GUTPAN_LOGO_w.png': '데스크톱 로고',
    'assets/main_music.mp3': '배경 음악'
}

# 파일 체크 함수
def check_required_files():
    missing_files = []
    for file_path, description in REQUIRED_FILES.items():
        if not os.path.exists(file_path):
            missing_files.append(f"{description} ({file_path})")
    return missing_files

# AI 모델 초기화
try:
    speech_recognizer = pipeline(
        "automatic-speech-recognition",
        model="kresnik/wav2vec2-large-xlsr-korean"
    )
    text_analyzer = pipeline(
        "sentiment-analysis",
        model="nlptown/bert-base-multilingual-uncased-sentiment"
    )
    print("✅ AI 모델 초기화 성공")
except Exception as e:
    print(f"❌ AI 모델 초기화 실패: {e}")
    speech_recognizer = None
    text_analyzer = None

# API 설정
HF_API_TOKEN = os.getenv("roots", "")
if not HF_API_TOKEN:
    print("Warning: HuggingFace API token not found. Some features may be limited.")

API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"} if HF_API_TOKEN else {}

# 상수 정의
WELCOME_MESSAGE = """
# 디지털 굿판에 오신 것을 환영합니다

이곳은 현대 도시 속에서 잊혀진 전통 굿의 정수를 담아낸 디지털 의례의 공간입니다. 
이곳에서는 사람들의 목소리와 감정을 통해 영적 교감을 나누고, 자연과 도시의 에너지가 연결됩니다.
"""

ONCHEON_STORY = """
## 생명의 공간 '온천천' 🌌

온천천의 물줄기는 신성한 금샘에서 시작됩니다. 금샘은 생명과 창조의 원천이며, 
천상의 생명이 지상에서 숨을 틔우는 자리입니다. 

도시의 소음 속에서도 신성한 생명력을 느껴보세요. 이곳에서 영적인 교감을 경험하며, 
자연과 하나 되는 순간을 맞이해 보시기 바랍니다.

이 프로젝트는 부산광역시 동래구 '온천장역'에서 금정구 '장전역'을 잇는 구간의 
온천천 산책로의 사운드스케이프를 기반으로 제작되었습니다.

산책로를 따라 걸으며 본 프로젝트 체험 시 보다 몰입된 경험이 가능합니다.
"""

# 초기 상태 정의
INITIAL_STATE = {
    "user_name": "",
    "baseline_features": None,
    "reflections": [],
    "wish": None,
    "final_prompt": "",
    "image_path": None,
    "current_tab": 0,
    "audio_playing": False
}

class SimpleDB:
    def __init__(self, reflections_path="data/reflections.json", wishes_path="data/wishes.json"):
        self.reflections_path = reflections_path
        self.wishes_path = wishes_path
        os.makedirs('data', exist_ok=True)
        self.reflections = self._load_json(reflections_path)
        self.wishes = self._load_json(wishes_path)

    def _load_json(self, file_path):
        if not os.path.exists(file_path):
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump([], f, ensure_ascii=False, indent=2)
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"Error loading {file_path}: {e}")
            return []

    def save_reflection(self, name, reflection, sentiment, timestamp=None):
        if timestamp is None:
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        reflection_data = {
            "timestamp": timestamp,
            "name": name,
            "reflection": reflection,
            "sentiment": sentiment
        }
        self.reflections.append(reflection_data)
        self._save_json(self.reflections_path, self.reflections)
        return True

    def save_wish(self, name, wish, emotion_data=None, timestamp=None):
        if timestamp is None:
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        wish_data = {
            "name": name,
            "wish": wish,
            "emotion": emotion_data,
            "timestamp": timestamp
        }
        self.wishes.append(wish_data)
        self._save_json(self.wishes_path, self.wishes)
        return True

    def _save_json(self, file_path, data):
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"Error saving to {file_path}: {e}")
            return False

    def get_all_reflections(self):
        return sorted(self.reflections, key=lambda x: x["timestamp"], reverse=True)

    def get_all_wishes(self):
        return sorted(self.wishes, key=lambda x: x["timestamp"], reverse=True)

def calculate_baseline_features(audio_data):
    try:
        if isinstance(audio_data, tuple):
            sr, y = audio_data
            y = y.astype(np.float32)
        elif isinstance(audio_data, str):
            y, sr = librosa.load(audio_data, sr=16000)
        else:
            print("Unsupported audio format")
            return None

        if len(y) == 0:
            print("Empty audio data")
            return None

        features = {
            "energy": float(np.mean(librosa.feature.rms(y=y))),
            "tempo": float(librosa.feature.tempo(y=y, sr=sr)[0]),
            "pitch": float(np.mean(librosa.feature.zero_crossing_rate(y=y))),
            "volume": float(np.mean(np.abs(y))),
            "mfcc": librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13).mean(axis=1).tolist()
        }
        return features
    except Exception as e:
        print(f"Error calculating baseline: {str(e)}")
        return None

def map_acoustic_to_emotion(features, baseline_features=None):
    if features is None:
        return {
            "primary": "알 수 없음",
            "intensity": 0,
            "confidence": 0.0,
            "secondary": "",
            "characteristics": ["음성 분석 실패"],
            "details": {
                "energy_level": "0%",
                "speech_rate": "알 수 없음",
                "pitch_variation": "알 수 없음",
                "voice_volume": "알 수 없음"
            }
        }

    energy_norm = min(features["energy"] * 100, 100)
    tempo_norm = min(features["tempo"] / 200, 1)
    pitch_norm = min(features["pitch"] * 2, 1)

    if baseline_features:
        if baseline_features["energy"] > 0 and baseline_features["tempo"] > 0 and baseline_features["pitch"] > 0:
            energy_norm = (features["energy"] / baseline_features["energy"]) * 50
            tempo_norm = (features["tempo"] / baseline_features["tempo"])
            pitch_norm = (features["pitch"] / baseline_features["pitch"])

    emotions = {
        "primary": "",
        "intensity": energy_norm,
        "confidence": 0.0,
        "secondary": "",
        "characteristics": []
    }

    if energy_norm > 70:
        if tempo_norm > 0.6:
            emotions["primary"] = "기쁨/열정"
            emotions["characteristics"].append("빠르고 활기찬 말하기 패턴")
        else:
            emotions["primary"] = "분노/강조"
            emotions["characteristics"].append("강한 음성 강도")
        emotions["confidence"] = energy_norm / 100
    elif pitch_norm > 0.6:
        if energy_norm > 50:
            emotions["primary"] = "놀람/흥분"
            emotions["characteristics"].append("높은 음고와 강한 강세")
        else:
            emotions["primary"] = "관심/호기심"
            emotions["characteristics"].append("음고 변화가 큼")
        emotions["confidence"] = pitch_norm
    elif energy_norm < 30:
        if tempo_norm < 0.4:
            emotions["primary"] = "슬픔/우울"
            emotions["characteristics"].append("느리고 약한 음성")
        else:
            emotions["primary"] = "피로/무기력"
            emotions["characteristics"].append("낮은 에너지 레벨")
        emotions["confidence"] = (30 - energy_norm) / 30
    else:
        if tempo_norm > 0.5:
            emotions["primary"] = "평온/안정"
            emotions["characteristics"].append("균형잡힌 말하기 패턴")
        else:
            emotions["primary"] = "차분/진지"
            emotions["characteristics"].append("안정적인 음성 특성")
        emotions["confidence"] = 0.5

    emotions["details"] = {
        "energy_level": f"{energy_norm:.1f}%",
        "speech_rate": f"{'빠름' if tempo_norm > 0.6 else '보통' if tempo_norm > 0.4 else '느림'}",
        "pitch_variation": f"{'높음' if pitch_norm > 0.6 else '보통' if pitch_norm > 0.3 else '낮음'}",
        "voice_volume": f"{'큼' if features['volume'] > 0.7 else '보통' if features['volume'] > 0.3 else '작음'}"
    }

    return emotions

def analyze_voice(audio_data, state):
    if audio_data is None:
        return state, "음성을 먼저 녹음해주세요.", "", "", ""

    try:
        sr, y = audio_data
        y = y.astype(np.float32)
        
        if len(y) == 0:
            return state, "음성이 감지되지 않았습니다.", "", "", ""

        acoustic_features = calculate_baseline_features((sr, y))
        if acoustic_features is None:
            return state, "음성 분석에 실패했습니다.", "", "", ""

        # 음성 인식
        text = "음성 인식 모델을 불러올 수 없습니다."
        if speech_recognizer:
            try:
                transcription = speech_recognizer({"sampling_rate": sr, "raw": y.astype(np.float32)})
                text = transcription["text"]
            except Exception as e:
                print(f"Speech recognition error: {e}")
                text = "음성 인식 실패"

        # 음성 감정 분석
        voice_emotion = map_acoustic_to_emotion(acoustic_features, state.get("baseline_features"))

        # 텍스트 감정 분석
        text_sentiment = {"label": "unknown", "score": 0.0}
        text_result = "텍스트 감정 분석을 수행할 수 없습니다."
        if text_analyzer and text:
            try:
                text_sentiment = text_analyzer(text)[0]
                text_result = f"텍스트 감정 분석: {text_sentiment['label']} (점수: {text_sentiment['score']:.2f})"
            except Exception as e:
                print(f"Text analysis error: {e}")
                text_result = "텍스트 감정 분석 실패"

        voice_result = (
            f"음성 감정: {voice_emotion['primary']} "
            f"(강도: {voice_emotion['intensity']:.1f}%, 신뢰도: {voice_emotion['confidence']:.2f})\n"
            f"특징: {', '.join(voice_emotion['characteristics'])}\n"
            f"상세 분석:\n"
            f"- 에너지 레벨: {voice_emotion['details']['energy_level']}\n"
            f"- 말하기 속도: {voice_emotion['details']['speech_rate']}\n"
            f"- 음높이 변화: {voice_emotion['details']['pitch_variation']}\n"
            f"- 음성 크기: {voice_emotion['details']['voice_volume']}"
        )

        # 프롬프트 생성
        prompt = generate_detailed_prompt(text, voice_emotion, text_sentiment)
        state = {**state, "final_prompt": prompt}

        return state, text, voice_result, text_result, prompt

    except Exception as e:
        print(f"Error in analyze_voice: {str(e)}")
        return state, f"오류 발생: {str(e)}", "", "", ""

def generate_detailed_prompt(text, emotions, text_sentiment):
    emotion_colors = {
        "기쁨/열정": "밝은 노랑과 따뜻한 주황색",
        "분노/강조": "강렬한 빨강과 짙은 검정",
        "놀람/흥분": "선명한 파랑과 밝은 보라",
        "관심/호기심": "연한 하늘색과 민트색",
        "슬픔/우울": "어두운 파랑과 회색",
        "피로/무기력": "탁한 갈색과 짙은 회색",
        "평온/안정": "부드러운 초록과 베이지",
        "차분/진지": "차분한 남색과 깊은 보라"
    }

    abstract_elements = {
        "기쁨/열정": "상승하는 나선형과 빛나는 입자들",
        "분노/강조": "날카로운 지그재그와 폭발하는 형태",
        "놀람/흥분": "물결치는 동심원과 반짝이는 점들",
        "관심/호기심": "부드럽게 흐르는 곡선과 floating shapes",
        "슬픔/우울": "하강하는 흐름과 흐릿한 그림자",
        "피로/무기력": "느리게 흐르는 물결과 흐려지는 형태",
        "평온/안정": "부드러운 원형과 조화로운 기하학적 패턴",
        "차분/진지": "균형잡힌 수직선과 안정적인 구조"
    }

    prompt = (
        f"minimalistic abstract art, {emotion_colors.get(emotions['primary'], '자연스러운 색상')} color scheme, "
        f"{abstract_elements.get(emotions['primary'], '유기적 형태')}, "
        "korean traditional patterns, ethereal atmosphere, sacred geometry, "
        "flowing energy, mystical aura, no human figures, no faces, "
        "digital art, high detail, luminescent effects. "
        "negative prompt: photorealistic, human, face, figurative, text, letters, "
        "--ar 2:3 --s 750 --q 2"
    )

    return prompt

def generate_image_from_prompt(prompt):
    if not prompt:
        print("No prompt provided")
        return None

    try:
        response = requests.post(
            API_URL,
            headers=headers,
            json={
                "inputs": prompt,
                "parameters": {
                    "negative_prompt": "ugly, blurry, poor quality, distorted",
                    "num_inference_steps": 30,
                    "guidance_scale": 7.5
                }
            }
        )

        if response.status_code == 200:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            image_path = f"generated_images/image_{timestamp}.png"
            os.makedirs("generated_images", exist_ok=True)
            
            with open(image_path, "wb") as f:
                f.write(response.content)
            
            return image_path
        else:
            print(f"Error: {response.status_code}")
            print(f"Response: {response.text}")
            return None
    except Exception as e:
        print(f"Error generating image: {str(e)}")
        return None

def encode_image_to_base64(image_path):
    try:
        if not os.path.exists(image_path):
            print(f"Warning: Image file not found at {image_path}")
            return ""
        with open(image_path, "rb") as img_file:
            return base64.b64encode(img_file.read()).decode()
    except Exception as e:
        print(f"Error encoding image {image_path}: {e}")
        return ""

def create_html_templates(mobile_logo, desktop_logo, main_image):    
    logo_html = f"""
    <div class="logo-container">
        <img class="mobile-logo" src="data:image/png;base64,{mobile_logo}" alt="디지털 굿판 로고 모바일">
        <img class="desktop-logo" src="data:image/png;base64,{desktop_logo}" alt="디지털 굿판 로고 데스크톱">
    </div>
    """

    main_image_html = f"""
    <div class="main-image-container">
        <img src="data:image/png;base64,{main_image}" alt="디지털 굿판 메인 이미지" class="main-image">
    </div>
    """

    audio_player_html = """
    <div class="audio-player-container">
        <audio controls class="audio-player">
            <source src="/assets/main_music.mp3" type="audio/mpeg">
            브라우저가 오디오 태그를 지원하지 않습니다.
        </audio>
    </div>
    """

    return logo_html, main_image_html, audio_player_html


# CSS 스타일 정의
STYLE_CSS = """
/* 기본 컨테이너 스타일링 */
.gradio-container {
    margin: 0 auto !important;
    max-width: 800px !important;
    padding: 1rem !important;
}

/* 이미지 컨테이너 스타일링 */
.main-image-container {
    width: 100%;
    margin: 0 auto 2rem auto;
    text-align: center;
}

.main-image {
    width: 100%;
    height: auto;
    max-width: 100%;
    display: block;
    margin: 0 auto;
}

/* 로고 스타일링 */
.logo-container { 
    padding: 20px 0;
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
    text-align: center;
}

/* 오디오 플레이어 스타일링 */
.audio-player-container {
    width: 100%;
    max-width: 800px;
    margin: 20px auto;
    text-align: center;
}

.audio-player {
    width: 100%;
    max-width: 300px;
    margin: 0 auto;
    border-radius: 8px;
}

/* 상태 메시지 박스 스타일링 */
.blessing-status-box {
    min-height: 200px !important;
    max-height: 300px !important;
    overflow-y: auto !important;
    padding: 15px !important;
    border: 1px solid #ddd !important;
    border-radius: 8px !important;
    background-color: #f8f9fa !important;
    margin: 10px 0 !important;
}

.blessing-status-box p {
    margin: 0 0 10px 0 !important;
    line-height: 1.5 !important;
}

/* 버튼 스타일링 */
.gradio-button {
    transition: all 0.3s ease;
    border-radius: 8px !important;
    width: 100% !important;
    margin: 5px 0 !important;
    min-height: 44px !important;
}

.gradio-button:active {
    transform: scale(0.98);
}

/* 데이터프레임 스타일링 */
.gradio-dataframe {
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    overflow: hidden;
}

/* 모바일 뷰 (600px 이하) */
@media (max-width: 600px) {
    .mobile-logo { 
        display: none !important; 
    }
    .desktop-logo {
        display: block !important;
        width: 100%;
        height: auto;
        max-width: 800px;
        margin: 0 auto;
    }
    .main-image {
        width: 100%;
        max-width: 100%;
    }
    .container { 
        padding: 10px !important; 
    }
    .gradio-row { 
        flex-direction: column !important;
        gap: 10px !important;
    }
    .audio-player {
        width: 100%;
    }
}

/* 데스크톱 뷰 (601px 이상) */
@media (min-width: 601px) {
    .desktop-logo { 
        display: none !important; 
    }
    .mobile-logo {
        display: block !important;
        width: 100% !important;
        height: auto !important;
        max-width: 300px !important;
        margin: 0 auto !important;
    }
    .main-image {
        width: 600px;
        max-width: 600px;
    }
    .gradio-row {
        gap: 20px !important;
    }
    .gradio-row > .gradio-column {
        flex: 1 !important;
        min-width: 0 !important;
    }
}

/* 컴포넌트 간격 조정 */
.gradio-column > *:not(:last-child) {
    margin-bottom: 1rem !important;
}
"""

def create_interface():
    # DB 초기화
    db = SimpleDB()
    
    # 이미지 인코딩
    mobile_logo = encode_image_to_base64("static/DIGITAL_GUTPAN_LOGO_m.png")
    desktop_logo = encode_image_to_base64("static/DIGITAL_GUTPAN_LOGO_w.png")
    main_image = encode_image_to_base64("static/main-image.png")
    
    # HTML 템플릿 생성
    logo_html, main_image_html, audio_player_html = create_html_templates(
        mobile_logo, desktop_logo, main_image
    )

    # 이벤트 핸들러들
    def handle_name_submit(name, state):
        if not name.strip():
            return (
                gr.update(visible=True),
                gr.update(visible=False),
                gr.update(visible=False),
                gr.update(visible=False),
                state
            )
        state = safe_state_update(state, {"user_name": name})
        return (
            gr.update(visible=False),
            gr.update(visible=True),
            gr.update(visible=False),
            gr.update(visible=False),
            state
        )

    def handle_continue():
        return (
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=True),
            gr.update(visible=False)
        )
    
    def handle_blessing_complete(audio, state):
        if audio is None:
            return state, "음성을 먼저 녹음해주세요.", gr.update(visible=True), gr.update(visible=False)
        
        try:
            sr, y = audio
            features = calculate_baseline_features((sr, y))
            
            if features:
                state = safe_state_update(state, {"baseline_features": features})
                return (
                    state,
                    "분석이 완료되었습니다. 다음 단계로 진행해주세요.",
                    gr.update(visible=False),
                    gr.update(visible=True)
                )
            
            return (
                state,
                "분석에 실패했습니다. 다시 시도해주세요.",
                gr.update(visible=True),
                gr.update(visible=False)
            )
            
        except Exception as e:
            return state, f"오류 발생: {str(e)}", gr.update(visible=True), gr.update(visible=False)
    
    def handle_enter():
        return gr.update(selected=1)

    def handle_save_reflection(text, state):
        if not text.strip():
            return state, []
        
        try:
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            name = state.get("user_name", "익명")
            
            if text_analyzer:
                sentiment = text_analyzer(text)[0]
                sentiment_text = f"{sentiment['label']} ({sentiment['score']:.2f})"
            else:
                sentiment_text = "분석 불가"
    
            db.save_reflection(name, text, sentiment_text)
            return state, [[current_time, text, sentiment_text]]
                
        except Exception as e:
            print(f"Error saving reflection: {e}")
            return state, []

    def handle_save_wish(text, state):
        if not text.strip():
            return "소원을 입력해주세요.", []
        
        try:
            name = state.get("user_name", "익명")
            db.save_wish(name, text)
            wishes = db.get_all_wishes()
            wish_display_data = [
                [wish["timestamp"], wish["wish"], wish["name"]]
                for wish in wishes
            ]
            return "소원이 저장되었습니다.", wish_display_data
        except Exception as e:
            print(f"Error saving wish: {e}")
            return "오류가 발생했습니다.", []

    def safe_analyze_voice(audio_data, state):
        if audio_data is None:
            return (
                state,
                "음성을 먼저 녹음해주세요.",
                "",
                "",
                "",
                "분석 준비 중..."
            )
    
        try:
            status_msg = "음성 분석 중..."
            sr, y = audio_data
            
            if len(y) == 0:
                return (
                    state,
                    "음성이 감지되지 않았습니다.",
                    "",
                    "",
                    "",
                    "분석 실패"
                )
    
            acoustic_features = calculate_baseline_features((sr, y))
            new_state, text, voice_result, text_result, prompt = analyze_voice(audio_data, state)
    
            return (
                new_state,
                text,
                voice_result,
                text_result,
                prompt,
                "분석 완료"
            )
    
        except Exception as e:
            print(f"Voice analysis error: {str(e)}")
            return (
                state,
                "음성 분석 중 오류가 발생했습니다. 다시 시도해주세요.",
                "",
                "",
                "",
                "분석 실패"
            )

    # Gradio 인터페이스 구성
    with gr.Blocks(theme=gr.themes.Soft(), css=STYLE_CSS) as app:
        # 상태 관리
        state = gr.State(value=INITIAL_STATE)
        processing_status = gr.State("")   

        # 로고 영역
        with gr.Column(elem_classes="logo-container"):
            gr.HTML(logo_html)

        # 탭 구성
        with gr.Tabs(selected=0) as tabs:
            # 입장 탭
            with gr.TabItem("입장") as tab_entrance:
                # 메인 이미지 표시
                gr.HTML(main_image_html)
                
                # 1단계: 첫 화면
                welcome_section = gr.Column(visible=True)
                with welcome_section:
                    gr.Markdown(WELCOME_MESSAGE)
                    name_input = gr.Textbox(
                        label="이름을 알려주세요",
                        placeholder="이름을 입력해주세요",
                        interactive=True
                    )
                    name_submit_btn = gr.Button("축원의식 준비하기", variant="primary")
            
                # 2단계: 세계관 설명
                story_section = gr.Column(visible=False)
                with story_section:
                    gr.Markdown(ONCHEON_STORY)
                    continue_btn = gr.Button("축원의식 시작하기", variant="primary")
            
                # 3단계: 축원 의식
                blessing_section = gr.Column(visible=False)
                with blessing_section:
                    gr.Markdown("### 축원의식을 시작하겠습니다")
                    gr.Markdown("'명짐 복짐 짊어지고 안가태평하시기를 비도발원 축원 드립니다'")
                    
                    baseline_audio = gr.Audio(
                        label="축원 문장 녹음하기",
                        sources=["microphone"],
                        type="numpy",
                        streaming=False
                    )
                    
                    blessing_status = gr.Markdown(
                        "분석 결과가 여기에 표시됩니다.", 
                        elem_id="blessing-status",
                        elem_classes="blessing-status-box"
                    )
                    
                    set_baseline_btn = gr.Button("축원문 분석하기", variant="primary")
                    send_blessing_btn = gr.Button("축원 보내기", variant="secondary", visible=False)

                # 4단계: 굿판 입장 안내
                entry_guide_section = gr.Column(visible=False)
                with entry_guide_section:
                    gr.Markdown("## 굿판으로 입장하기")
                    gr.Markdown("""
                    * 청신 탭으로 이동해 주세요.
                    * 부산광역시 동래구 온천장역에서 시작하면 더욱 깊은 경험을 시작할 수 있습니다.
                    * (본격적인 경험을 시작하기에 앞서 이동을 권장드립니다)
                    """)
                    enter_btn = gr.Button("청신 의식 시작하기", variant="primary")

            # 청신 탭
            with gr.TabItem("청신") as tab_listen:
                gr.Markdown("## 청신 - 소리로 정화하기")
                gr.Markdown("""
                온천천의 소리를 들으며 마음을 정화해보세요.
                
                💫 이 앱은 온천천의 사운드스케이프를 녹음하여 제작되었으며,
                온천천 온천장역에서 장전역까지 걸으며 더 깊은 체험이 가능합니다.
                """)
                
                gr.Markdown("## 온천천의 소리를 들어보세요")
                gr.HTML(audio_player_html)
                
                with gr.Column():
                    reflection_input = gr.Textbox(
                        label="지금 이 순간의 감상을 자유롭게 적어보세요",
                        lines=3,
                        max_lines=5
                    )
                    save_btn = gr.Button("감상 저장하기", variant="secondary")
                    reflections_display = gr.Dataframe(
                        headers=["시간", "감상", "감정 분석"],
                        label="기록된 감상들",
                        value=[],
                        interactive=False,
                        wrap=True,
                        row_count=(5, "dynamic")
                    )

            # 기원 탭
            with gr.TabItem("기원") as tab_wish:
                gr.Markdown("## 기원 - 소원을 전해보세요")
                status_display = gr.Markdown("", visible=False)
                
                with gr.Row():
                    with gr.Column():
                        voice_input = gr.Audio(
                            label="소원을 나누고 싶은 마음을 말해주세요",
                            sources=["microphone"],
                            type="numpy",
                            streaming=False,
                            elem_id="voice-input"
                        )
                        with gr.Row():
                            clear_btn = gr.Button("녹음 지우기", variant="secondary")
                            analyze_btn = gr.Button("소원 분석하기", variant="primary")
                    
                    with gr.Column():
                        transcribed_text = gr.Textbox(
                            label="인식된 텍스트",
                            interactive=False
                        )
                        voice_emotion = gr.Textbox(
                            label="음성 감정 분석",
                            interactive=False
                        )
                        text_emotion = gr.Textbox(
                            label="텍스트 감정 분석",
                            interactive=False
                        )

            # 송신 탭
            with gr.TabItem("송신") as tab_send:
                gr.Markdown("## 송신 - 소지(소원지)를 그려 날려 태워봅시다")
                final_prompt = gr.Textbox(
                    label="생성된 프롬프트",
                    interactive=False,
                    lines=3
                )
                generate_btn = gr.Button("마음의 그림 그리기", variant="primary")
                result_image = gr.Image(
                    label="생성된 이미지",
                    show_download_button=True
                )
                
                gr.Markdown("## 온천천에 전하고 싶은 소원을 남겨주세요")
                final_reflection = gr.Textbox(
                    label="소원",
                    placeholder="당신의 소원을 한 줄로 남겨주세요...",
                    max_lines=3
                )
                save_final_btn = gr.Button("소원 전하기", variant="primary")
                gr.Markdown("""
                💫 여러분의 소원은 11월 25일 온천천 벽면에 설치될 소원나무에 전시될 예정입니다.
                따뜻한 마음을 담아 작성해주세요.
                """)
                wishes_display = gr.Dataframe(
                    headers=["시간", "소원", "이름"],
                    label="기록된 소원들",
                    value=[],
                    interactive=False,
                    wrap=True
                )

            # 프로젝트 소개 탭
            with gr.TabItem("프로젝트 소개") as tab_intro:
                gr.HTML(main_image_html)
                gr.Markdown("""
                # 디지털 굿판 프로젝트
                '디지털 굿판'은 부산문화재단의 지원으로 루츠리딤이 제작한 다원예술 프로젝트입니다.
                
                본 사업은 전통 굿의 요소와 현대 기술을 결합해 참여자들이 자연과 깊이 연결되며 내면을 탐색하고 치유하는 경험을 제공합니다.
                
                금샘과 온천천의 생명 창조 신화를 배경으로, 참여자들은 자연의 소리에 귀를 기울이고, 신화에 몰입하며, 감정을 표현하는 과정에서 개인적 및 공동체적 치유의 여정을 걷습니다.
                
                AI와 사운드스케이프 같은 현대 기술, 장소성, 신화적 요소가 어우러져 삶과 예술, 자연과 기술이 조화를 이루는 체험 공간을 창조합니다.
                
                이 프로젝트는 현대 사회의 삶에 대한 근본적인 질문을 던지며 새로운 문화적 지향점을 모색합니다.

                본 프로젝트에서 기록된 정보 중 '송신' 단계의 '소원전하기'를 제외한 모든 과정의 정보는(목소리,감상 등) 별도로 저장되지 않으며 AI 학습이나 외부 공유에 사용되지 않습니다.

                ## 크레딧
                - **기획**: 루츠리딤, 전승아
                - **음악**: 루츠리딤 (이광혁)
                - **미디어아트**: 송지훈
                """)

# 이벤트 연결
        name_submit_btn.click(
            fn=handle_name_submit,
            inputs=[name_input, state],
            outputs=[welcome_section, story_section, blessing_section, entry_guide_section, state]
        )

        continue_btn.click(
            fn=handle_continue,
            outputs=[story_section, welcome_section, blessing_section, entry_guide_section]
        )

        set_baseline_btn.click(
            fn=handle_blessing_complete,
            inputs=[baseline_audio, state],
            outputs=[state, blessing_status, blessing_section, entry_guide_section]
        )

        enter_btn.click(
            fn=handle_enter,
            outputs=[tabs]
        )

        save_btn.click(
            fn=handle_save_reflection,
            inputs=[reflection_input, state],
            outputs=[state, reflections_display]
        )

        clear_btn.click(
            fn=lambda: None,
            outputs=[voice_input]
        )

        analyze_btn.click(
            fn=safe_analyze_voice,
            inputs=[voice_input, state],
            outputs=[state, transcribed_text, voice_emotion, text_emotion, final_prompt, status_display]
        )

        generate_btn.click(
            fn=generate_image_from_prompt,
            inputs=[final_prompt],
            outputs=[result_image]
        )

        save_final_btn.click(
            fn=handle_save_wish,
            inputs=[final_reflection, state],
            outputs=[blessing_status, wishes_display]
        )

    return app

if __name__ == "__main__":
    # 필요한 디렉토리 생성
    for directory in REQUIRED_DIRS:
        os.makedirs(directory, exist_ok=True)
    
    # 파일 경로 체크
    print("\n🔍 파일 경로 확인 중...")
    missing_files = []
    for file_path, description in REQUIRED_PATHS.items():
        if not os.path.exists(file_path):
            missing_files.append(f"{description} ({file_path})")
    
    if missing_files:
        print("\n❌ 누락된 파일들:")
        for file in missing_files:
            print(f"- {file}")
    else:
        print("\n✅ 모든 필요 파일이 존재합니다.")

    # PWA 설정 파일 생성
    create_pwa_files()
    
    print("\n🎵 음악 파일 접근성 확인...")
    if os.path.exists("assets/main_music.mp3"):
        print("✅ 음악 파일 확인됨")
        print(f"📂 절대 경로: {os.path.abspath('assets/main_music.mp3')}")
    else:
        print("❌ 음악 파일이 없습니다")

    print("\n🚀 서버 시작...")
    
    # Gradio 앱 실행
    demo = create_interface()
    demo.queue().launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        debug=True,
        show_error=True,
        height=None,
        width="100%"
    )