File size: 74,608 Bytes
dddc22b
 
bb63470
 
33cb0be
1914fcd
dddc22b
 
8b6ea6c
36c54bd
 
90b9d37
 
36c54bd
 
 
 
5156ec3
 
1914fcd
36c54bd
 
2f16de0
1914fcd
36c54bd
1914fcd
e006b08
1914fcd
 
 
dddc22b
1914fcd
b7baa07
dddc22b
 
33cb0be
bed0080
 
33cb0be
bed0080
 
33cb0be
 
 
 
 
 
 
 
 
 
 
 
6000375
bed0080
 
 
1914fcd
33cb0be
bed0080
33cb0be
 
 
 
1914fcd
bed0080
 
33cb0be
 
bed0080
 
 
33cb0be
 
 
bed0080
 
33cb0be
 
 
 
 
 
 
 
 
 
 
 
 
 
bed0080
 
33cb0be
 
1914fcd
 
 
 
 
 
 
 
 
36c54bd
1914fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158bfd0
0acbc79
158bfd0
 
d7b7fbe
158bfd0
 
 
 
 
 
36c54bd
 
 
 
0acbc79
 
d7b7fbe
eefb51e
0acbc79
 
 
 
 
 
 
 
 
36c54bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0acbc79
 
 
 
 
2f16de0
eefb51e
 
 
0acbc79
 
 
 
 
 
 
 
 
1914fcd
0acbc79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158bfd0
 
0acbc79
158bfd0
0acbc79
6f76a92
 
 
 
 
 
 
 
2f16de0
158bfd0
6f76a92
36c54bd
4991658
 
 
 
 
6f76a92
1914fcd
 
6f76a92
 
 
 
 
 
 
 
 
 
 
1914fcd
6f76a92
1914fcd
 
 
6f76a92
 
 
 
 
 
 
 
 
 
 
158bfd0
0acbc79
6f76a92
158bfd0
 
6f76a92
4991658
0acbc79
36c54bd
6f76a92
0acbc79
1914fcd
33cb0be
c425828
33cb0be
 
 
 
 
 
 
 
 
 
 
57c75c6
 
 
 
 
 
 
 
 
 
 
c425828
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914fcd
 
 
 
 
33cb0be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914fcd
 
 
 
 
 
 
 
 
 
 
 
a4c78d2
 
1914fcd
a4c78d2
 
 
 
1914fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4c78d2
 
 
 
 
 
 
 
1914fcd
 
 
 
dddc22b
1914fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8101c4f
1914fcd
 
99145d6
1914fcd
8101c4f
1914fcd
a4c78d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2ae042
 
 
 
99145d6
 
e2ae042
 
 
 
 
 
 
 
 
 
8101c4f
99145d6
8101c4f
a4c78d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2ae042
 
a4c78d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2ae042
 
 
 
 
 
a4c78d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2ae042
a4c78d2
 
 
 
 
 
 
 
 
 
 
 
e2ae042
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8101c4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914fcd
 
 
8101c4f
1914fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
e2ae042
1914fcd
e2ae042
1914fcd
 
 
 
33cb0be
1914fcd
 
 
 
 
 
 
 
b7baa07
1914fcd
 
 
 
a9c15ac
1914fcd
 
 
 
 
 
c425828
1914fcd
 
 
a9c15ac
1914fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4709eba
b7baa07
 
03598da
b7baa07
 
 
57e126d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914fcd
 
 
 
 
 
 
b7baa07
1914fcd
 
3a61dd1
57e126d
 
3a61dd1
57e126d
 
 
 
1914fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
488e761
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914fcd
 
 
 
3a61dd1
57e126d
 
3a61dd1
57e126d
 
 
 
1914fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7baa07
1914fcd
 
 
 
 
 
 
488e761
1914fcd
 
b7baa07
1914fcd
 
 
 
 
 
 
b7baa07
1914fcd
 
 
4709eba
1914fcd
 
 
 
34cd2ff
1914fcd
 
 
 
 
 
488e761
 
 
1914fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
488e761
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914fcd
488e761
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914fcd
 
 
 
 
 
 
b7baa07
1914fcd
 
 
 
 
 
 
 
 
 
 
940be28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914fcd
8101c4f
99145d6
8101c4f
e2ae042
 
 
99145d6
e2ae042
 
 
99145d6
e2ae042
 
 
99145d6
e2ae042
 
 
 
 
 
 
99145d6
e2ae042
99145d6
e2ae042
 
 
 
 
 
 
 
 
 
99145d6
e2ae042
 
 
 
 
 
99145d6
e2ae042
 
 
 
 
 
 
 
99145d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2ae042
 
 
99145d6
e2ae042
 
8101c4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47d9b1a
8101c4f
57e126d
 
8101c4f
 
47d9b1a
 
8101c4f
47d9b1a
8101c4f
 
 
 
47d9b1a
 
1914fcd
33cb0be
1914fcd
 
a9c15ac
3010d56
a9c15ac
2aa50fa
1089706
1914fcd
1089706
b7baa07
1914fcd
1089706
2b97308
 
 
 
 
 
 
1089706
5156ec3
6ee33cd
2b97308
 
 
 
5156ec3
1089706
2b97308
 
 
0787a0a
940be28
0787a0a
940be28
 
567bf65
1914fcd
2b97308
 
6f76a92
 
 
 
567bf65
44204df
 
 
 
567bf65
940be28
567bf65
4a1861f
567bf65
1914fcd
2b97308
38bdcec
8101c4f
 
 
 
 
 
 
2b97308
38bdcec
 
44204df
 
8101c4f
57e126d
 
8101c4f
0787a0a
44204df
 
 
 
38bdcec
 
2b97308
0787a0a
38bdcec
2b97308
541e490
9955abb
d0049ca
 
471f68e
 
 
 
 
 
 
3cb1977
471f68e
16a6426
 
 
 
d0049ca
 
16a6426
d0049ca
471f68e
d0049ca
16a6426
 
471f68e
16a6426
 
 
 
 
 
 
 
 
 
 
 
 
 
471f68e
16a6426
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0049ca
 
 
471f68e
541e490
 
9377efb
541e490
 
 
9300635
541e490
 
 
 
2b97308
541e490
 
1089706
2b97308
 
 
38bdcec
 
 
 
 
 
 
 
 
 
 
1914fcd
541e490
2b97308
 
 
38bdcec
2b97308
 
34cd2ff
1914fcd
2b97308
 
 
 
34cd2ff
2b97308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38bdcec
 
 
 
 
 
 
 
 
 
 
2b97308
 
 
 
 
 
 
 
 
 
1914fcd
2b97308
 
 
 
 
 
 
 
b09bb8a
38bdcec
 
2b97308
 
 
 
 
 
 
24a8312
03598da
24a8312
e3bbd03
 
 
d23e904
e3bbd03
0787a0a
e3bbd03
 
24a8312
e3bbd03
24a8312
e3bbd03
 
 
38bdcec
e3bbd03
 
d23e904
 
38bdcec
01c0d7d
e3bbd03
 
 
 
 
24a8312
 
 
e3bbd03
bed0080
1914fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fbaf37
1914fcd
4fbaf37
1914fcd
 
dd927a9
 
 
 
1914fcd
dd927a9
940be28
1914fcd
 
 
dd927a9
 
1914fcd
 
940be28
dd927a9
 
 
 
 
 
 
940be28
dd927a9
 
 
1914fcd
dd927a9
 
44204df
dd927a9
 
940be28
1914fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9300635
 
 
1914fcd
 
 
 
 
 
 
 
c425828
1914fcd
 
 
 
 
 
c425828
 
 
 
 
 
 
 
 
 
 
 
1914fcd
 
 
c425828
 
 
 
 
 
 
1914fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c425828
1914fcd
 
 
 
c425828
1914fcd
c425828
1914fcd
c425828
1914fcd
c425828
 
1914fcd
c425828
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1914fcd
 
 
c425828
 
1914fcd
22303ab
 
 
4fbaf37
22303ab
542130b
22303ab
 
4fbaf37
22303ab
542130b
22303ab
 
 
542130b
940be28
542130b
22303ab
4ff2c6d
22303ab
 
 
542130b
22303ab
 
 
 
542130b
22303ab
541e490
22303ab
187437e
22303ab
187437e
22303ab
 
 
187437e
22303ab
542130b
22303ab
 
 
542130b
22303ab
1914fcd
33cb0be
0dfe358
131e4f2
 
 
 
 
 
 
 
 
 
90b9d37
 
 
131e4f2
90b9d37
 
 
131e4f2
90b9d37
 
 
131e4f2
 
 
 
 
33cb0be
3fd9a97
 
90b9d37
 
3ed65ad
 
3fd9a97
 
 
 
 
 
 
 
 
 
68dacdb
 
9f6e4e4
 
 
 
 
 
 
68dacdb
90b9d37
7c45562
90b9d37
00c16e9
 
 
 
 
 
 
 
 
f6ae55f
bf9c7d7
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
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
import os
import json
import numpy as np
import librosa
from datetime import datetime
from flask import Flask, send_from_directory, render_template
import gradio as gr
from transformers import pipeline
import requests
from dotenv import load_dotenv

app = Flask(__name__)

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

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

"""

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

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

도시의 소음 속에서도 신성한 생명력을 느껴보세요. 이곳에서 영적인 교감을 경험하며, 자연과 하나 되는 순간을 맞이해 보시기 바랍니다
 
이 프로젝트는 부산광역시 동래구 ‘온천장역’ 에서 금정구 ‘장전역’을 잇는 구간의 온천천 산책로의 사운드 스케이프를  기반으로 제작 되었습니다.

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


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 self.wishes

# 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 {}

# 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"
    )
except Exception as e:
    print(f"Error initializing AI models: {e}")
    speech_recognizer = None
    text_analyzer = None

# 필요한 디렉토리 생성
os.makedirs("generated_images", exist_ok=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, "음성 분석에 실패했습니다.", "", "", ""

        # 음성 인식
        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 = "음성 인식 실패"
        else:
            text = "음성 인식 모델을 불러올 수 없습니다."

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

        # 텍스트 감정 분석
        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_sentiment = {"label": "unknown", "score": 0.0}
                text_result = "텍스트 감정 분석 실패"
        else:
            text_sentiment = {"label": "unknown", "score": 0.0}
            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",
        "슬픔/우울": "하강하는 흐름과 흐릿한 그림자",
        "피로/무기력": "느리게 흐르는 물결과 흐려지는 형태",
        "평온/안정": "부드러운 원형과 조화로운 기하학적 패턴",
        "차분/진지": "균형잡힌 수직선과 안정적인 구조"
    }

    # 텍스트에서 주요 감정 키워드 추출
    text_emotions = text_sentiment["label"].lower().split(", ")
    emotion_keywords = set()
    for emotion in text_emotions:
        for key in emotion_colors.keys():
            if emotion in key.lower():
                emotion_keywords.add(key)
    
    # 기본 프롬프트 구성
    prompt = f"minimalistic abstract art, "
    
    # 주요 감정 색상과 요소 통합
    colors = []
    elements = []
    for emotion in emotion_keywords:
        if emotion in emotion_colors:
            colors.append(emotion_colors[emotion])
            elements.append(abstract_elements[emotion])
    
    prompt += f"{', '.join(colors) if colors else emotion_colors[emotions['primary']]} color scheme, "
    prompt += f"{', '.join(elements) if elements else abstract_elements[emotions['primary']]}, "
    
    # 기본 요소 추가
    prompt += "korean traditional patterns, ethereal atmosphere, sacred geometry, "
    prompt += "flowing energy, mystical aura, no human figures, no faces, "
    prompt += "digital art, high detail, luminescent effects. "
    prompt += "negative prompt: photorealistic, human, face, figurative, text, letters, "
    prompt += "--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 create_pwa_files():
    """PWA 필요 파일들 생성"""
    # manifest.json 생성
    manifest_path = 'static/manifest.json'
    if not os.path.exists(manifest_path):
        manifest_data = {
            "name": "디지털 굿판",
            "short_name": "디지털 굿판",
            "description": "현대 도시 속 디지털 의례 공간",
            "start_url": "/",
            "display": "standalone",
            "background_color": "#0b0f19",
            "theme_color": "#0b0f19",
            "orientation": "portrait",
            "categories": ["art", "entertainment"],
            "lang": "ko",
            "dir": "ltr",
            "prefer_related_applications": false,
            "icons": [
                {
                    "src": "/static/icons/icon-72x72.png",
                    "sizes": "72x72",
                    "type": "image/png",
                    "purpose": "any maskable"
                },
                {
                    "src": "/static/icons/icon-96x96.png",
                    "sizes": "96x96",
                    "type": "image/png",
                    "purpose": "any maskable"
                },
                {
                    "src": "/static/icons/icon-128x128.png",
                    "sizes": "128x128",
                    "type": "image/png",
                    "purpose": "any maskable"
                },
                {
                    "src": "/static/icons/icon-144x144.png",
                    "sizes": "144x144",
                    "type": "image/png",
                    "purpose": "any maskable"
                },
                {
                    "src": "/static/icons/icon-152x152.png",
                    "sizes": "152x152",
                    "type": "image/png",
                    "purpose": "any maskable"
                },
                {
                    "src": "/static/icons/icon-192x192.png",
                    "sizes": "192x192",
                    "type": "image/png",
                    "purpose": "any maskable"
                },
                {
                    "src": "/static/icons/icon-384x384.png",
                    "sizes": "384x384",
                    "type": "image/png",
                    "purpose": "any maskable"
                },
                {
                    "src": "/static/icons/icon-512x512.png",
                    "sizes": "512x512",
                    "type": "image/png",
                    "purpose": "any maskable"
                }
            ],
            "screenshots": [
                {
                    "src": "/static/screenshots/screenshot1.png",
                    "sizes": "1280x720",
                    "type": "image/png",
                    "label": "홈 화면"
                }
            ]
        }
        with open(manifest_path, 'w', encoding='utf-8') as f:
            json.dump(manifest_data, f, ensure_ascii=False, indent=2)

    # service-worker.js 생성
    sw_path = 'static/service-worker.js'
    if not os.path.exists(sw_path):
        with open(sw_path, 'w', encoding='utf-8') as f:
            f.write('''
// 캐시 이름 설정
const CACHE_NAME = 'digital-gutpan-v1';

// 캐시할 파일 목록
const urlsToCache = [
  '/',
  '/static/icons/icon-72x72.png',
  '/static/icons/icon-96x96.png',
  '/static/icons/icon-128x128.png',
  '/static/icons/icon-144x144.png',
  '/static/icons/icon-152x152.png',
  '/static/icons/icon-192x192.png',
  '/static/icons/icon-384x384.png',
  '/static/icons/icon-512x512.png',
  '/assets/main_music.mp3'
];

// 서비스 워커 설치 시
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(urlsToCache))
      .then(() => self.skipWaiting())
  );
});

// 서비스 워커 활성화 시
self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheName !== CACHE_NAME) {
            return caches.delete(cacheName);
          }
        })
      );
    }).then(() => self.clients.claim())
  );
});

// 네트워크 요청 처리
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        if (response) {
          return response;
        }
        return fetch(event.request);
      })
  );
});
            '''.strip())

    # index.html 파일에 화면 꺼짐 방지 스크립트 추가
    index_path = 'templates/index.html'
    if not os.path.exists(index_path):
        with open(index_path, 'w', encoding='utf-8') as f:
            f.write('''<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>디지털 굿판</title>
    <link rel="manifest" href="/manifest.json">
    <meta name="theme-color" content="#0b0f19">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="디지털 굿판">
    <meta name="description" content="현대 도시 속 디지털 의례 공간">
    
    <!-- iOS에서의 앱 아이콘 -->
    <link rel="apple-touch-icon" href="/static/icons/icon-192x192.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/static/icons/icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/static/icons/icon-180x180.png">
    <link rel="apple-touch-icon" sizes="167x167" href="/static/icons/icon-167x167.png">

    <!-- iOS 스플래시 스크린 -->
    <link rel="apple-touch-startup-image" href="/static/splash/apple-splash-2048-2732.png" media="(device-width: 1024px) and (device-height: 1366px) and (-webkit-device-pixel-ratio: 2)">
    <link rel="apple-touch-startup-image" href="/static/splash/apple-splash-1668-2388.png" media="(device-width: 834px) and (device-height: 1194px) and (-webkit-device-pixel-ratio: 2)">
    <link rel="apple-touch-startup-image" href="/static/splash/apple-splash-1536-2048.png" media="(device-width: 768px) and (device-height: 1024px) and (-webkit-device-pixel-ratio: 2)">
    <link rel="apple-touch-startup-image" href="/static/splash/apple-splash-1125-2436.png" media="(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3)">
    <link rel="apple-touch-startup-image" href="/static/splash/apple-splash-828-1792.png" media="(device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2)">
    
    <style>
        /* iOS 상태바 영역 보호 */
        body {
            padding-top: env(safe-area-inset-top);
            background: #0b0f19 !important;
            color: #ffffff;
        }
        .status-bar {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: env(safe-area-inset-top);
            background: black;
            z-index: 1000;
        }
        #gradio-app {
            background: #0b0f19 !important;
        }
         .install-prompt {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: #2a2f3e;
            color: white;
            padding: 15px 20px;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            display: none;
            z-index: 1000;
            width: 90%;
            max-width: 400px;
            text-align: center;
        }

        .install-button {
            background: #4a90e2;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            margin-top: 10px;
            cursor: pointer;
            font-weight: bold;
        }

        .close-prompt {
            position: absolute;
            top: 5px;
            right: 10px;
            background: none;
            border: none;
            color: white;
            font-size: 20px;
            cursor: pointer;
        }
    </style>
    <script>
        let deferredPrompt;

        window.addEventListener('beforeinstallprompt', (e) => {
            e.preventDefault();
            deferredPrompt = e;
            showInstallPrompt();
        });

        function showInstallPrompt() {
            const prompt = document.createElement('div');
            prompt.className = 'install-prompt';
            prompt.innerHTML = `
                <button class="close-prompt">&times;</button>
                <p>디지털 굿판을 앱으로 설치하여 더 나은 경험을 누려보세요!</p>
                <button class="install-button">앱 설치하기</button>
            `;
            document.body.appendChild(prompt);

            // 설치 프롬프트 표시
            setTimeout(() => {
                prompt.style.display = 'block';
            }, 2000);

            // 닫기 버튼
            prompt.querySelector('.close-prompt').addEventListener('click', () => {
                prompt.remove();
            });

            // 설치 버튼
            prompt.querySelector('.install-button').addEventListener('click', async () => {
                if (deferredPrompt) {
                    deferredPrompt.prompt();
                    const { outcome } = await deferredPrompt.userChoice;
                    if (outcome === 'accepted') {
                        console.log('사용자가 앱 설치를 수락했습니다');
                    }
                    deferredPrompt = null;
                    prompt.remove();
                }
            });
        }

        // iOS Safari에서 설치 안내
        if (navigator.standalone === false && navigator.userAgent.match(/Safari/i)) {
            setTimeout(() => {
                const iosPrompt = document.createElement('div');
                iosPrompt.className = 'install-prompt';
                iosPrompt.innerHTML = `
                    <button class="close-prompt">&times;</button>
                    <p>iOS에서 설치하기:<br>
                    1. 공유 버튼을 탭하세요 📤<br>
                    2. "홈 화면에 추가"를 선택하세요 ➕</p>
                `;
                document.body.appendChild(iosPrompt);
                iosPrompt.style.display = 'block';

                iosPrompt.querySelector('.close-prompt').addEventListener('click', () => {
                    iosPrompt.remove();
                });
            }, 2000);
        }
        // 페이지 로드 시 상단으로 스크롤
        window.addEventListener('load', function() {
            setTimeout(() => {
                window.scrollTo(0, 0);
            }, 100);
        });
        async function preventSleep() {
            try {
                if ('wakeLock' in navigator) {
                    const wakeLock = await navigator.wakeLock.request('screen');
                    console.log('화면 켜짐 유지 활성화');
                    
                    document.addEventListener('visibilitychange', async () => {
                        if (document.visibilityState === 'visible') {
                            await preventSleep();
                        }
                    });
                }
            } catch (err) {
                console.log('화면 켜짐 유지 실패:', err);
            }
        }

        if ('serviceWorker' in navigator) {
            window.addEventListener('load', async () => {
                try {
                    const registration = await navigator.serviceWorker.register('/static/service-worker.js');
                    console.log('ServiceWorker 등록 성공:', registration.scope);
                    await preventSleep();
                } catch (err) {
                    console.log('ServiceWorker 등록 실패:', err);
                }
            });
        }
        
        // 화면 꺼짐 방지
        async function preventSleep() {
            try {
                if ('wakeLock' in navigator) {
                    const wakeLock = await navigator.wakeLock.request('screen');
                    console.log('화면 켜짐 유지 활성화');
                    
                    document.addEventListener('visibilitychange', async () => {
                        if (document.visibilityState === 'visible') {
                            await preventSleep();
                        }
                    });
                }
            } catch (err) {
                console.log('화면 켜짐 유지 실패:', err);
            }
        }

        // 로딩 상태 관리 함수들
        function showLoading(buttonId, loadingText) {
            // 버튼 비활성화
            const button = document.getElementById(buttonId);
            if (button) {
                button.disabled = true;
                button.innerHTML = loadingText;
            }
            
            // 로딩 오버레이 표시
            const overlay = document.createElement('div');
            overlay.className = 'processing-overlay';
            overlay.innerHTML = `
                <div class="loading-spinner"></div>
                <div class="loading-text">${loadingText}</div>
            `;
            document.body.appendChild(overlay);
        }

        function hideLoading(buttonId, originalText) {
            // 버튼 활성화
            const button = document.getElementById(buttonId);
            if (button) {
                button.disabled = false;
                button.innerHTML = originalText;
            }
            
            // 로딩 오버레이 제거
            const overlay = document.querySelector('.processing-overlay');
            if (overlay) {
                overlay.remove();
            }
        }

        // PWA 설치 관련
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', async () => {
                try {
                    const registration = await navigator.serviceWorker.register('/service-worker.js');
                    console.log('ServiceWorker 등록 성공:', registration.scope);
                    await preventSleep();
                } catch (err) {
                    console.log('ServiceWorker 등록 실패:', err);
                }
            });
        }
    </script>
</head>
<body>
    <div class="status-bar"></div>
    <div id="gradio-app"></div>
    <div class="footer-spacing"></div>
</body>
</html>''')

def safe_state_update(state, updates):
    try:
        new_state = {**state, **updates}
        # 중요 상태값 검증
        if "user_name" in updates:
            new_state["user_name"] = str(updates["user_name"]).strip() or "익명"
        if "baseline_features" in updates:
            if updates["baseline_features"] is None:
                return state  # baseline이 None이면 상태 업데이트 하지 않음
        return new_state
    except Exception as e:
        print(f"State update error: {e}")
        return state

def create_interface():
    db = SimpleDB()
    import base64
    
    # initial_state 정의
    initial_state = {
        "user_name": "",
        "baseline_features": None,
        "reflections": [],  # 여기에 사용자의 모든 기록을 누적
        "wish": None,
        "final_prompt": "",
        "image_path": None,
        "current_tab": 0
    }
    
    def encode_image_to_base64(image_path):
        try:
            with open(image_path, "rb") as img_file:
                return base64.b64encode(img_file.read()).decode()
        except Exception as e:
            print(f"이미지 로딩 에러 ({image_path}): {e}")
            return ""
    
    # 로고 이미지 인코딩
    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")

    if not mobile_logo or not desktop_logo:
        logo_html = """
            <div style="text-align: center; padding: 20px;">
                <h1 style="font-size: 24px;">디지털 굿판</h1>
            </div>
        """
    else:
        logo_html = f"""
            <img class="mobile-logo" src="data:image/png;base64,{mobile_logo}" alt="디지털 굿판 로고 모바일">
            <img class="desktop-logo" src="data:image/png;base64,{desktop_logo}" alt="디지털 굿판 로고 데스크톱">
        """

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

    # 모바일 및 데스크톱용 위치 이미지를 Base64로 인코딩
    location_image_mobile = encode_image_to_base64("static/location.png")
    location_image_desktop = encode_image_to_base64("static/location_w.png")
    
    # location_html 정의
    if not location_image_mobile or not location_image_desktop:
        location_html = """
            <div style="text-align: center; padding: 20px;">
                <h2>위치 안내</h2>
            </div>
        """
    else:
        location_html = f"""
            <img class="location-image-mobile" src="data:image/png;base64,{location_image_mobile}" alt="위치 안내 이미지 (모바일)">
            <img class="location-image-desktop" src="data:image/png;base64,{location_image_desktop}" alt="위치 안내 이미지 (데스크톱)">
        """

    css = """
        /* 전체 컨테이너 width 제한 */
        .gradio-container {
            margin: 0 auto !important;
            max-width: 800px !important;
            padding: 1rem !important;
        }

        /* 모바일 뷰 */
        @media (max-width: 600px) {
            .location-image-desktop { 
                display: none !important; 
            }
            .location-image-mobile {
                display: block !important;
                width: 100%;
                height: auto;
            }
            .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%;
            }
            .gradio-container, .gradio-container *, body {
                font-size: 17px !important;
            }
            
            .markdown-style h1,
            .markdown-style h1 * {
                font-size: 22px !important;
            }
            
            .markdown-style h2,
            .markdown-style h2 * {
                font-size: 20px !important;
            }
            
            .markdown-style h3,
            .markdown-style h3 * {
                font-size: 18px !important;
            }
        }
        
        /* 데스크톱 뷰 (601px 이상) */
        @media (min-width: 601px) {
            .location-image-mobile { 
                display: none !important; 
            }
            .location-image-desktop {
                display: block !important;
                width: 100%;
                height: auto;
            }
            .main-image {
                width: 600px;
                max-width: 600px;
            }
            .container { padding: 10px !important; }
            .gradio-row { 
                flex-direction: column !important;
                gap: 10px !important;
            }
            .gradio-button { 
                width: 100% !important; 
                margin: 5px 0 !important;
                min-height: 44px !important;
            }
            .gradio-textbox { width: 100% !important; }
            .gradio-audio { width: 100% !important; }
            .gradio-image { width: 100% !important; }
            #audio-recorder { width: 100% !important; }
            #result-image { width: 100% !important; }
            .gradio-dataframe {
                overflow-x: auto !important;
                max-width: 100% !important;
            }
            .logo-container { 
                padding: 20px 0;
                width: 100%;
                max-width: 800px;
                margin: 0 auto;
            }
            .desktop-logo { 
                display: none !important; 
            }
            .mobile-logo {
                display: block !important;
                width: 100% !important;
                height: auto !important;
                max-width: 300px !important;
                margin: 0 auto !important;
            }
            /* 데스크탑에서 2단 컬럼 레이아웃 보완 */
            .gradio-row {
                gap: 20px !important;
            }
            .gradio-row > .gradio-column {
                flex: 1 !important;
                min-width: 0 !important;
            }
        }
    
        /* 전반적인 UI 개선 */
        .gradio-button {
            transition: all 0.3s ease;
            border-radius: 8px !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;
         }

        .gradio-button:active {
            transform: scale(0.98);
        }
        
        /* 컴포넌트 간격 조정 */
        .gradio-column > *:not(:last-child) {
            margin-bottom: 1rem !important;
        }
        
        /* 데이터프레임 스타일링 */
        .gradio-dataframe {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            overflow: hidden;
        }
        .gradio-dataframe table {
            font-size: 16px !important;
        }
        /* 오디오 플레이어 컨테이너 */
        .audio-player-container {
            max-width: 800px;
            margin: 20px auto;
            padding: 0 1rem;
        }
        .audio-player {
            margin: 20px auto;
            width: 100%;
            max-width: 300px;
        
        /* 탭 스타일링 */
        .tabs {
            max-width: 800px;
            margin: 0 auto;
        }
        
        /* 마크다운 컨텐츠 */
        .markdown-content {
            max-width: 800px;
            margin: 0 auto;
            padding: 0 1rem;
        }

        /* 기본 텍스트 크기 증가 */
        .gradio-container, .gradio-container *, body {
            font-size: 17px !important;
            line-height: 1.7 !important;
        }
        
        /* 마크다운 기본 텍스트 */
        .markdown-style {
            font-size: 17px !important;
            line-height: 1.7 !important;
        }
        
        /* 마크다운 제목 크기 조정 */
        .markdown-style h1,
        .markdown-style h1 * {
            font-size: 22px !important;
            line-height: 1.4 !important;
            margin-bottom: 0.8em !important;
        }
        
        .markdown-style h2,
        .markdown-style h2 * {
            font-size: 20px !important;
            line-height: 1.4 !important;
            margin-bottom: 0.7em !important;
        }
        
        .markdown-style h3,
        .markdown-style h3 * {
            font-size: 18px !important;
            line-height: 1.4 !important;
            margin-bottom: 0.6em !important;
        }
        
        /* 입력 필드와 버튼 */
        .gradio-textbox input,
        .gradio-textbox textarea {
            font-size: 17px !important;
            line-height: 1.5 !important;
            padding: 12px !important;
        }
        
        .gradio-button {
            font-size: 17px !important;
            padding: 12px 20px !important;
            min-height: 48px !important;
        }
        
        /* 탭과 라벨 */
        .tabs .tab-nav * {
            font-size: 17px !important;
        }
        
        label, .label-text {
            font-size: 17px !important;
            margin-bottom: 8px !important;
        }
    
        /* 이미지 컨테이너 */
        .gradio-image {
            border-radius: 8px;
            overflow: hidden;
            max-width: 800px;
            margin: 0 auto;
        }

        .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 {
            min-height: 250px !important;
            max-height: 400px !important;
            overflow-y: auto !important;
            padding: 20px !important;
            border: 1px solid #ddd !important;
            border-radius: 12px !important;
            background-color: #f8f9fa !important;
            margin: 15px 0 !important;
            font-size: 16px !important;
            line-height: 1.6 !important;
        }
        
        .blessing-status-box h3 {
            color: #2a5d8f !important;
            margin-bottom: 15px !important;
        }
        
        .blessing-status-box strong {
            color: #4a90e2 !important;
        }
        }
        
     /* Hugging Face 로고 숨기기 */
        .div.gr-header {
            display: none !important;
        }
        
        /* 다크 테마 기본 스타일 */
        body {
            margin: 0;
            padding: 0;
            background: #0b0f19 !important;
            overflow-x: hidden;
            position: relative;
            min-height: 100vh;
            color: #ffffff;
        }
        
        /* 메인 컨테이너 스타일링 */
        .gradio-container {
            margin: 0 auto !important;
            padding: 0 !important;
            max-width: 800px !important;
            background: #0b0f19 !important;
            min-height: 100vh;
            box-shadow: 0 0 10px rgba(0,0,0,0.3);
            position: relative;
        }
        
        /* 상단 상태바 스타일 */
        .status-bar {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: env(safe-area-inset-top);
            background: #000000;
            z-index: 1000;
        }
        
        /* 하단 여백 조정 */
        .footer-spacing {
            height: env(safe-area-inset-bottom);
            background: #0b0f19;
        }
        
        /* 앱 스크롤 동작 */
        .app-scroll {
            -webkit-overflow-scrolling: touch;
            scroll-behavior: smooth;
        }
        
        /* 모든 탭 컨텐츠 배경색 */
        .tabs > div {
            background: #0b0f19 !important;
        }
        
        /* 입력 필드 스타일링 */
        .gradio-textbox input,
        .gradio-textbox textarea {
            background: #1a1f2e !important;
            color: #ffffff !important;
            border: 1px solid #2a2f3e !important;
        }
        
        /* 버튼 스타일링 유지 */
        .gradio-button {
            background: #2a2f3e !important;
            color: #ffffff !important;
            border: none !important;
        }
        
        .gradio-button:hover {
            background: #3a3f4e !important;
        }
        
        /* 데이터프레임/테이블 스타일링 */
        .gradio-dataframe {
            background: #1a1f2e !important;
            color: #ffffff !important;
        }
        
        /* 모달과 팝업의 배경색 */
        .modal-content {
            background: #0b0f19 !important;
            color: #ffffff !important;
        }
        
        /* iOS 상태바용 메타 태그 색상 */
        @supports (-webkit-touch-callout: none) {
            .status-bar {
                height: max(env(safe-area-inset-top), 20px);
                background: #000000;
            }
        }
            /* 로딩 상태 표시 */
        .processing-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(11, 15, 25, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #4a90e2;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        .loading-text {
            position: absolute;
            top: 60%;
            left: 50%;
            transform: translateX(-50%);
            color: white;
            font-size: 18px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 버튼 비활성화 스타일 */
        .gradio-button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
    
        /* 이미지 컨테이너 스타일 */
        .location-image-container {
            width: 100%;
            max-width: 800px;
            margin: 20px auto;
            text-align: center;
        }
        
        .location-image {
            width: 100%;
            max-width: 100%;
            height: auto;
            border-radius: 12px;
            margin: 0 auto;
        }

        }
    """

    with gr.Blocks(theme=gr.themes.Soft(), css=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
                    )
                    
                    # 분석 버튼을 바로 녹음기 아래에 배치
                    set_baseline_btn = gr.Button("축원문 분석하기", variant="primary")
                    
                    # 상태 표시창 - 분석 결과 표시
                    blessing_status = gr.Markdown(
                        value="축원 문장을 녹음한 후 분석하기 버튼을 눌러주세요.", 
                        elem_id="blessing-status",
                        elem_classes="blessing-status-box"
                    )

            with gr.TabItem("청신") as tab_listen:
                gr.Markdown("## 청신 - 신을 부르기 위한 정화 의식")
                # 온천 이미지 추가
                oncheon_image = encode_image_to_base64("static/oncheon.png")
                gr.HTML(f"""
                <div class="oncheon-image-container">
                    <img src="data:image/png;base64,{oncheon_image}" alt="온천천 이미지" class="oncheon-image">
                </div>
                """)
                gr.Markdown("""
                **청신(淸神)** 단계는 신을 부르는 의식으로, 정화와 연결의 의미를 담고 있습니다. 
                이 단계에서는 참여자가 도시의 번잡함에서 벗어나 내면의 고요함을 찾고 신성과의 교감을 시작하게 됩니다.

                본격적인 의식을 시작하기 전, 마음을 정화하고 감각을 열어 경험에 몰입할 준비를 마치세요
                """)
                with gr.Column():
                    gr.HTML(location_html)
                gr.Markdown("""
                ### 보다 몰입된 경험을 위해  
                이 경험은 부산 동래구 온천장역에서 시작하여, 금정구 장전역까지 온천천을 따라 신화적 공간과 연결될 수 있도록 설계되었습니다. 
                특히 이곳에서 시작하면 온천천의 자연스러운 소리와 금샘의 생명력을 더욱 깊이 느낄 수 있습니다. 
                온천천을 따라 걷다 보면, 금샘과 연결된 물의 정화 에너지가 스며들며 신성을 느끼게 될 것입니다.
            
                청신 단계의 목적은 참여자들이 자연과 신화적 요소를 통해 감각을 깨우고 자신의 감정을 정화하며, 초자연적 존재와 소통할 준비를 하는 데 있습니다. 
                특히 온천천의 물소리와 자연의 소리는 신을 부르는 소리처럼 참여자의 마음을 고요하게 하고, 금샘 신화의 정화와 생명력의 상징성을 통해 신을 맞이할 준비를 갖추게 합니다.
                
                ### 이제 음악을 들으며 감정을 기록해보세요. 
                음악을 통해 내면의 평온을 되찾고, 이 과정에서 느껴지는 감정과 생각들을 자유롭게 적어보세요. 이 기록은 이후 과정에서 소망과 의식을 구체화하는 데 큰 도움이 될 것입니다.
                """)
                
                # 커스텀 오디오 플레이어
                gr.Markdown("## 聽身, 請神 (몸의 소리를 듣고 신을 청하다) ")
                gr.HTML("""
                <div class="soundcloud-container">
                    <iframe 
                        width="100%" 
                        height="166" 
                        scrolling="no" 
                        frameborder="no" 
                        allow="autoplay" 
                        src="https://w.soundcloud.com/player/?url=https%3A//soundcloud.com/rootsredeem/23931633-2169-46de-b990-d7fc1c8661b2%3Fsi%3D5a147740c1c548fe9b5cb911bbd41373&color=%23ff5500&auto_play=true&hide_related=true&show_comments=false&show_user=false&show_reposts=false&show_teaser=false"
                    ></iframe>
                    </div>
                    <div class="player-description">
                        음악을 들으며 마음을 정화하고 내면의 소리에 귀를 기울여보세요.
                    </div>
                </div>
                <style>
                    .player-container {
                        width: 100%;
                        max-width: 800px;
                        margin: 20px auto;
                        padding: 20px;
                        background: #f8f9fa;
                        border-radius: 12px;
                        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                    }
                    
                    .player-title {
                        font-size: 1.2em;
                        font-weight: bold;
                        margin-bottom: 15px;
                        color: #2a5d8f;
                        text-align: center;
                    }
                    
                    .soundcloud-container {
                        width: 100%;
                        border-radius: 8px;
                        overflow: hidden;
                        margin: 10px 0;
                    }
                    
                    .player-description {
                        margin-top: 15px;
                        text-align: center;
                        color: #666;
                        font-size: 0.9em;
                    }
            
                    @media (max-width: 600px) {
                        .player-container {
                            padding: 15px;
                            margin: 10px auto;
                        }
                        
                        .player-title {
                            font-size: 1.1em;
                        }
                    }
                </style>
                """)
                                                                    
                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("## 기원 - 소망을 천명하고 신에게 바라는 의식체")
                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"  # elem_id 추가
                        )
                        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("## 송신 - 신과 내 마음을 보내다")
                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월 28-29일 부산대 지하철역 인근 온천천 벽면에 설치될 소원나무에 전시될 예정입니다.
                따뜻한 마음을 담아 작성해주세요.
                """)
                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 기술, 음악, 자연, 그리고 일상 공간이 융합된 독창적 경험을 제공합니다. 참여자는 이 의례적 경험을 통해 내면의 정화와 신성에의 초월적 연결을 체험하고, 일상과 신성의 경계를 허물며 삶의 본질에 대한 질문을 던지게 됩니다.

            
                ### 디지털 굿판은 세 가지 주요 의례적 단계로 구성됩니다:
            
                1. **청신(淸神)**: 정화와 신성에의 준비 과정으로, 참여자가 도시의 번잡함에서 벗어나 자연과 신화적 소리를 통해 내면을 정화합니다. 온천천의 물소리와 루츠리딤의 음악은 굿 의식의 정화 단계를 음악으로 변형하여, 신을 부르는 초월적 의식에 몰입하게 합니다.
                
                2. **기원**: 참여자는 자신의 감정과 소망을 발화하여 의례적 상징성을 더합니다. 강신무의 트랜스 경험을 재현한 음악과 함께, AI가 발화된 감정을 분석하고 이를 시각적 데이터로 변환합니다. 이 시각화는 금샘의 신화적 상징성을 재해석하여 개인의 소망을 신성과 연결하는 예술적 매개체로 작용합니다.
                
                3. **송신**: 마지막 단계에서는 정화와 기원을 거쳐 구체화된 소망을 상징적 시각 표현으로 전환하여 외부로 전달합니다. AI와 디지털 기술이 결합하여 참여자의 내면적 바람을 외부로 확장하고, 예술적 시각 언어를 통해 신성에 도달하는 과정을 형상화합니다.
            
                **디지털 굿판**은 전통 신화와 예술, 첨단 AI 기술이 융합하여 신과 인간의 교감, 내면과 외부의 경계를 탐구하는 예술적 시도입니다. 전통적 굿의 치유적 효과를 현대의 감각적 경험으로 체화하며, 예술과 기술의 융합을 통해 새로운 의례와 감정의 형식을 제안합니다. 이 프로젝트는 전통을 기반으로 한 감각적 초월의 경험을 디지털 시대의 언어로 재해석하여, 예술의 확장 가능성과 현대 사회에서의 치유적 역할을 고찰하는 다원예술의 새로운 지평을 제시합니다.

                ## 루츠리딤
                세계 각 국의 전통장단을 연구하고 현대적으로 재해석하는 월드뮤직 트랜스 그룹. 종으로는 정통과 현대를, 횡으로는 동양과 서양을 한데 아우르며 새로운 장르의 차별화된 월드뮤직을 개척
                국악기로 서양음악을 연주하는 평범한 퓨전국악 프레임에서 탈피, 동서양의 콜라보레이션으로 퓨처국악을 표방하는 실험적 예술단체입니다.
                Instagram [@roots_redeem](https://www.instagram.com/roots_redeem/)


                ## 윤리조항
                디지털 굿판은 현대 사회에서 예술과 기술이 교차하는 지점에서, 삶과 치유에 대한 근본적인 질문을 던집니다. 프로젝트 중 기록된 모든 정보(목소리, 감상 등)는 ‘송신’ 단계의 ‘소원전하기’를 제외하고는 별도로 저장되지 않으며, AI 학습이나 외부 공유에 사용되지 않습니다.
            
                ## CREDITS
            
                - **기획**: 루츠리딤, 전승아
                - **음악**: 루츠리딤 (이광혁)
                - **미디어아트**: 송지훈
                """)               

        # 이벤트 핸들러들
        def handle_name_submit(name, state):
            if not name.strip():
                return (
                    gr.update(visible=True),
                    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),
                state
            )
        
        def handle_continue():
            return (
                gr.update(visible=False),
                gr.update(visible=False),
                gr.update(visible=True)
            )

        
        def handle_blessing_complete(audio, state):
            # 분석 중 메시지 표시
            initial_status = "분석 중입니다. 잠시만 기다려주세요..."
            
            # 오디오가 없을 경우 바로 메시지 반환
            if audio is None:
                return state, "축원 문장을 먼저 녹음해주세요.", initial_status
            
            try:
                sr, y = audio
                features = calculate_baseline_features((sr, y))
        
                # 분석이 완료된 경우
                if features:
                    state = safe_state_update(state, {"baseline_features": features})
                    detailed_msg = f"""
                    ### 축원 분석이 완료되었습니다
                    
                    **음성 특성 분석:**
                    - 음성 강도: {features['energy']:.2f}
                    - 음성 속도: {features['tempo']:.2f}
                    - 음성 높낮이: {features['pitch']:.2f}
                    - 음성 크기: {features['volume']:.2f}
                    
                    축원이 완료되었습니다. 이제 청신 탭으로 이동하여 의식을 진행해주세요.
                    """
                    return state, detailed_msg, ""  # 초기 상태는 비워서 완료 상태로 만듭니다.
                
                # 분석 실패 시 메시지
                return state, "분석에 실패했습니다. 다시 시도해주세요.", initial_status
        
            except Exception as e:
                return state, f"오류가 발생했습니다: {str(e)}", initial_status
                
        def handle_enter():
            return gr.update(selected=1)  # 청신 탭으로 이동

        def handle_start():
            return gr.update(visible=False), gr.update(visible=True)

        def handle_baseline(audio, current_state):
            if audio is None:
                return current_state, "음성을 먼저 녹음해주세요.", gr.update(selected=0)
            
            try:
                sr, y = audio
                y = y.astype(np.float32)
                features = calculate_baseline_features((sr, y))
                if features:
                    current_state = safe_state_update(current_state, {
                        "baseline_features": features,
                        "current_tab": 1
                    })
                    return current_state, "기준점이 설정되었습니다. 청신 탭으로 이동합니다.", gr.update(selected=1)
                return current_state, "기준점 설정에 실패했습니다. 다시 시도해주세요.", gr.update(selected=0)
            except Exception as e:
                print(f"Baseline error: {str(e)}")
                return current_state, "오류가 발생했습니다. 다시 시도해주세요.", gr.update(selected=0)

        def move_to_chungshin():
            return gr.Tabs.update(selected="청신")
        
        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 = "분석 불가"
        
                # 현재 사용자의 기존 reflections 가져오기
                if "reflections" not in state:
                    state["reflections"] = []
                
                # 새로운 reflection 추가
                new_reflection = {
                    "timestamp": current_time,
                    "text": text,
                    "sentiment": sentiment_text
                }
                state["reflections"].append(new_reflection)
                
                # DB에 저장
                db.save_reflection(name, text, sentiment_text)
                
                # 화면에 표시할 데이터 생성 (현재 사용자의 모든 기록)
                display_data = [
                    [r["timestamp"], r["text"], r["sentiment"]]
                    for r in state["reflections"]
                ]
                
                return state, display_data
        
            except Exception as e:
                print(f"Error saving reflection: {e}")
                return state, []

        def save_reflection_fixed(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에 저장
                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)
                
                # 청신 단계의 누적된 기록들을 프롬프트에 통합
                if "reflections" in new_state:
                    accumulated_emotions = []
                    accumulated_texts = []
                    
                    for reflection in new_state["reflections"]:
                        accumulated_texts.append(reflection["text"])
                        if "sentiment" in reflection:
                            accumulated_emotions.append(reflection["sentiment"])
                    
                    # 프롬프트 생성 시 누적된 감정과 텍스트 반영
                    enhanced_prompt = generate_detailed_prompt(
                        text=f"{text} || Previous reflections: {' | '.join(accumulated_texts)}",
                        emotions=map_acoustic_to_emotion(acoustic_features, new_state.get("baseline_features")),
                        text_sentiment={"label": ", ".join(accumulated_emotions), "score": 1.0}
                    )
                    
                    return new_state, text, voice_result, text_result, enhanced_prompt, "분석 완료"
                    
                return new_state, text, voice_result, text_result, prompt, "분석 완료"
        
            except Exception as e:
                print(f"Voice analysis error: {str(e)}")
                return state, "음성 분석 중 오류가 발생했습니다.", "", "", "", "분석 실패"

        # 이벤트 연결
        name_submit_btn.click(
            fn=handle_name_submit,
            inputs=[name_input, state],
            outputs=[welcome_section, story_section, blessing_section, state]
        )
        
        continue_btn.click(
            fn=handle_continue,
            outputs=[story_section, welcome_section, blessing_section]
        )
        
        set_baseline_btn.click(
            fn=handle_blessing_complete,
            inputs=[baseline_audio, state],
            outputs=[state, blessing_status, processing_status]
        )
        
        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


@app.route('/static/<path:path>')
def serve_static(path):
    return send_from_directory('static', path)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/assets/<path:path>')
def serve_assets(path):
    return send_from_directory('assets', path)

@app.route('/manifest.json')
def serve_manifest():
    return send_from_directory('static', 'manifest.json')

@app.route('/service-worker.js')
def serve_service_worker():
    return send_from_directory('static', 'service-worker.js')

@app.route('/wishes/<path:path>')
def serve_wishes(path):
    return send_from_directory('data/wishes', path)


if __name__ == "__main__":
    # 환경변수 로드
    load_dotenv()
    
    # 필요한 디렉토리 생성
    required_dirs = [
        'static',
        'assets',
        'data',
        'generated_images',
        'templates'
    ]
    for directory in required_dirs:
        os.makedirs(directory, exist_ok=True)
    
    # PWA 파일 생성
    create_pwa_files()
    
    # 오디오 파일 체크
    audio_path = os.path.join('assets', 'main_music.mp3')
    if os.path.exists(audio_path):
        print(f"✅ Audio file found: {audio_path}")
        print(f"   Size: {os.path.getsize(audio_path)} bytes")
        print(f"   Absolute path: {os.path.abspath(audio_path)}")
    else:
        print(f"❌ Audio file not found: {audio_path}")

    # Gradio 인터페이스 생성
    demo = create_interface()
    
    # Gradio 앱 실행
    demo.queue().launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        debug=True,
        show_error=True,
        height=None,
        width="100%",
        favicon_path="static/icons/icon-72x72.png"
    )