File size: 37,925 Bytes
2bf5d9d
1a7b403
dd52c00
c03c3fd
1a7b403
 
 
2bf5d9d
 
1a7b403
5288426
1a7b403
4deaa88
2bf5d9d
1a7b403
 
 
9fdfed4
1a7b403
9fdfed4
2bf5d9d
 
4deaa88
 
 
 
 
 
 
 
 
 
 
 
2bf5d9d
4deaa88
 
 
1a7b403
2bf5d9d
4deaa88
1a7b403
4deaa88
1a7b403
 
2bf5d9d
1a7b403
 
ee57972
1a7b403
ee57972
 
1a7b403
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bf5d9d
4deaa88
 
 
 
 
5288426
 
 
4deaa88
 
1a7b403
4deaa88
 
1a7b403
 
ee57972
1a7b403
6f94f48
1a7b403
9fdfed4
1a7b403
 
6f94f48
1a7b403
 
4deaa88
1a7b403
 
6f94f48
1a7b403
7a5d869
c03c3fd
4deaa88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a7b403
 
 
 
 
 
ee57972
1a7b403
 
ee57972
1a7b403
 
ee57972
1a7b403
 
ee57972
7a5d869
 
 
 
 
6f94f48
69c6981
 
 
1a7b403
 
 
 
cc33a71
 
 
 
 
1a7b403
7a5d869
1a7b403
9fdfed4
 
1a7b403
9fdfed4
 
4deaa88
69c6981
 
9fdfed4
1a7b403
9fdfed4
1a7b403
 
 
 
 
69c6981
 
9fdfed4
69c6981
9fdfed4
69c6981
1a7b403
 
 
 
 
 
 
7a5d869
1a7b403
7a5d869
69c6981
9fdfed4
1a7b403
7a5d869
1a7b403
 
7a5d869
 
 
1a7b403
7a5d869
 
 
 
 
 
 
 
 
 
 
 
 
69c6981
 
9fdfed4
69c6981
9fdfed4
7a5d869
 
69c6981
 
9fdfed4
69c6981
 
 
 
7a5d869
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a7b403
 
 
298e0dc
69c6981
 
9fdfed4
69c6981
9fdfed4
69c6981
1a7b403
 
 
298e0dc
1a7b403
 
 
 
2bf5d9d
 
 
1a7b403
 
 
2bf5d9d
 
 
1a7b403
 
 
2bf5d9d
 
 
1a7b403
 
 
2bf5d9d
 
 
1a7b403
 
 
2bf5d9d
 
 
1a7b403
 
 
2bf5d9d
 
 
1a7b403
 
 
2bf5d9d
 
 
1a7b403
2bf5d9d
1a7b403
2bf5d9d
 
 
 
 
 
 
 
 
 
 
 
1a7b403
2bf5d9d
298e0dc
 
 
 
 
 
 
 
2bf5d9d
69c6981
 
 
 
 
2bf5d9d
4deaa88
 
 
 
298e0dc
1a7b403
69c6981
ee57972
4deaa88
298e0dc
1a7b403
69c6981
1a7b403
4deaa88
298e0dc
1a7b403
69c6981
1a7b403
 
 
69c6981
 
4deaa88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee57972
1a7b403
4deaa88
1a7b403
 
ee57972
4deaa88
 
 
1a7b403
 
 
 
dd52c00
1a7b403
 
4deaa88
 
 
1a7b403
 
 
 
 
 
 
7d16d28
1a7b403
 
7d16d28
1a7b403
 
7d16d28
 
 
 
 
 
4deaa88
 
 
 
 
 
 
 
 
 
 
 
 
1a7b403
 
 
 
 
 
 
c03c3fd
1a7b403
 
7a5d869
1a7b403
 
 
cc33a71
1a7b403
 
cc33a71
 
 
 
 
 
1a7b403
 
 
 
7d16d28
cc33a71
d19da7b
5288426
d19da7b
5288426
cc33a71
 
1a7b403
cc33a71
7d16d28
cc33a71
7d16d28
 
 
 
9fdfed4
d19da7b
cc33a71
 
1a7b403
 
7a5d869
1a7b403
 
 
 
69c6981
 
 
1a7b403
 
 
 
 
 
 
7d16d28
1a7b403
 
7d16d28
1a7b403
 
7d16d28
 
 
 
 
 
 
4deaa88
 
 
 
 
 
 
 
 
 
1a7b403
 
 
 
 
 
 
c03c3fd
1a7b403
7d16d28
 
 
1a7b403
 
c03c3fd
 
 
298e0dc
c03c3fd
 
 
1a7b403
 
 
 
69c6981
c03c3fd
1a7b403
 
 
 
 
 
 
7d16d28
 
 
 
 
 
 
1a7b403
 
 
69c6981
 
9fdfed4
69c6981
9fdfed4
69c6981
1a7b403
 
7d16d28
 
1a7b403
 
dd52c00
1a7b403
 
 
 
 
69c6981
1a7b403
 
 
 
7d16d28
1a7b403
 
 
 
 
7d16d28
cc33a71
7d16d28
 
cc33a71
7d16d28
 
 
 
1a7b403
4deaa88
 
 
 
 
 
 
 
dd52c00
 
4deaa88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a7b403
 
dd52c00
1a7b403
 
 
dd52c00
 
 
 
 
1a7b403
 
 
 
 
 
dd52c00
 
 
 
1a7b403
 
dd52c00
1a7b403
69c6981
 
9fdfed4
69c6981
 
1a7b403
dd52c00
 
 
1a7b403
 
69c6981
1a7b403
7a5d869
1a7b403
 
 
 
 
69c6981
 
9fdfed4
69c6981
9fdfed4
69c6981
1a7b403
 
 
c03c3fd
 
5288426
1a7b403
 
 
 
 
5288426
1a7b403
5288426
 
 
1a7b403
5288426
 
 
 
 
1a7b403
 
5288426
 
 
 
4deaa88
5288426
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a7b403
 
5288426
 
 
 
 
 
 
 
 
 
 
1a7b403
 
 
 
 
 
 
 
 
 
5288426
 
 
 
1a7b403
 
 
 
 
 
 
 
 
 
5288426
1a7b403
5288426
 
 
 
 
 
 
 
1a7b403
 
 
 
 
 
 
 
4deaa88
c03c3fd
4deaa88
c03c3fd
4deaa88
 
 
 
c03c3fd
4deaa88
c03c3fd
4deaa88
 
 
1a7b403
 
ee57972
1a7b403
 
69c6981
1a7b403
 
7a5d869
1a7b403
 
 
 
 
a035719
 
9fdfed4
a035719
9fdfed4
a035719
1a7b403
 
 
 
 
 
 
 
 
 
 
 
5288426
 
 
a035719
5288426
 
 
 
 
4deaa88
1a7b403
5288426
 
 
 
a035719
5288426
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a7b403
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4deaa88
 
 
 
 
 
 
a035719
4deaa88
a035719
4deaa88
 
 
1a7b403
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69c6981
1a7b403
69c6981
 
 
 
 
1a7b403
 
 
 
 
 
 
 
2bf5d9d
 
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
import streamlit as st
import numpy as np
import pprint
from decimal import Decimal

from gtts import gTTS
from collections import Counter
from streamlit_chat import message

from bots.judgement_bot import debate_judgement
from bots.perfect_case_bot import perfect_case_selector
import time
from time import strftime

from audiorecorder import audiorecorder

# modules
from modules.db_modules import get_db, put_item, get_item, get_lastest_item
from modules.gpt_modules import gpt_call, gpt_call_context
from modules.whisper_modules import whisper_transcribe


#########################################################
# GET DB
#########################################################
dynamodb = get_db()


#########################################################
# Time Stamp
#########################################################
tm = time.localtime()
time_stamp = strftime('%Y-%m-%d %I:%M:%S %p', tm)


#########################################################
# Page Configurations
#########################################################
st.set_page_config(page_title="Streamlit App")

#########################################################
# Initialize session state variables
#########################################################
if "page" not in st.session_state:
    st.session_state.page = "Page 1"

if "topic" not in st.session_state:
    st.session_state.topic = "None"

if "user_id" not in st.session_state:
    st.session_state.user_id = ""

if "case1" not in st.session_state:
    st.session_state.case1 = ""

if "case2" not in st.session_state:
    st.session_state.case2 = ""

if "case3" not in st.session_state:
    st.session_state.case3 = ""

if "page2_tab" not in st.session_state:
    st.session_state.page2_tab = "tab1"

if "total_debate_history" not in st.session_state:
    st.session_state.total_debate_history = []

if "user_debate_history" not in st.session_state:
    st.session_state.user_debate_history = []

if "bot_debate_history" not in st.session_state:
    st.session_state.bot_debate_history = []

if "user_debate_time" not in st.session_state:
    st.session_state.user_debate_time = ""

if "pros_and_cons" not in st.session_state:
    st.session_state.pros_and_cons = ""

if "start_time" not in st.session_state:
    st.session_state.start_time = time.time()

if "end_time" not in st.session_state:
    st.session_state.end_time = time.time()

if "debate_time" not in st.session_state:
    st.session_state.debate_time = 0

if "pre_audio" not in st.session_state:
    st.session_state.pre_audio = np.array([])


# for db session number
if "session_num" not in st.session_state:
    st.session_state.session_num = 0

if "judgement_result" not in st.session_state:
    st.session_state.judgement_result = ""


#########################################################
# Save function (placeholder)
#########################################################
def save_info(user_id):
    # You can add the code to save the submitted info (e.g., to a database)
    st.session_state.user_id = user_id

    print("User ID:", user_id)

# Session state
# session_state = SessionState.get(user_id="", openAI_token="", debate_theme="")
def write_info():
    st.write('You choose', st.session_state.topic_list)

# for callback when button is clicked
def page_1_2_controller():
    if st.session_state.user_id.strip() == "":
        st.session_state.page = "Page 1"
        st.warning('Please fill in all the required fields.')
    else:
        st.session_state.page = "Page 2"
        save_info(st.session_state.user_id)
        
        #########################################################
        # Session Update
        #########################################################
        debate_setting = get_lastest_item(
            table=dynamodb.Table('DEBO_debate_setting'),
            name_of_partition_key="user_id",
            value_of_partition_key=st.session_state.user_id,
            limit_num=1
        )
        # Session์ด ์—†๋‹ค๋ฉด, 0์œผ๋กœ ์ดˆ๊ธฐํ™”
        if debate_setting == []:
            st.session_state.session_num = 0
        # User์˜ ์ด์ „ ๊ธฐ๋ก์—์„œ Session์ด ์žˆ๋‹ค๋ฉด, Session Number๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  ๊ฐฑ์‹ ํ•จ
        else:
            st.session_state.session_num = debate_setting[0]['session_num']

def page_2_3_controller():
    st.session_state.page = "Page 3"

def page2_tab_controller():
    st.session_state.page2_tab = "tab2"

def page_3_4_controller():
    st.session_state.page = "Page 4"

def page_4_5_controller():
    st.session_state.page = "Page 5"

def page_5_6_controller():
    st.session_state.page = "Page 6"

def page_6_7_controller():
    st.session_state.page = "Page 7"

def page_2_7_controller():
    st.session_state.page = "Page 7"

def page_n_1_controller():
    st.session_state.page = "Page 1"

#########################################################
# Page 1
#########################################################
def page1():

    # ์ฒซํŽ˜์ด์ง€๋Š” home์ด ๋”ฐ๋กœ ํ•„์š”์—†์„ ๊ฒƒ ๊ฐ™์•„์„œ ์ฃผ์„์ฒ˜๋ฆฌํ•จ
    #_, _, _, home  = st.columns([5, 5, 1, 1])
    # with home:
    #     st.button("๐Ÿ”", on_click=page_n_1_controller, use_container_width=True)

    st.header('User Info')
    st.session_state.user_id = st.text_input(
        label='User ID',
        # key='user_id',
        max_chars=100,
        placeholder="Enter user ID",
    )
    
    st.button(
        label='Next',
        type='primary',
        on_click=page_1_2_controller
    )

#########################################################
# Page 2
#########################################################
def page2():
    _, _, pre, home  = st.columns([5, 5, 1, 1])
    with pre:
        st.button("๐Ÿ”™", on_click=page_n_1_controller, use_container_width=True)
    with home:
        st.button("๐Ÿ”", on_click=page_n_1_controller, use_container_width=True)

    st.header("Choose Option")
    option_result = st.selectbox("Choose your option", ["Total Debate", "Evaluation Only & Analyzing Utterances"])

    # add controller
    if option_result == "Total Debate":
        page_control_func = page_2_3_controller
    elif option_result == "Evaluation Only & Analyzing Utterances":
        page_control_func = page_2_7_controller

    st.button(
        label='Next',
        type='primary',
        on_click=page_control_func
    )
        

#########################################################
# Page 3
#########################################################
def page3():
    debate_history = get_lastest_item(
            table=dynamodb.Table('DEBO_debate_setting'),
            name_of_partition_key="user_id",
            value_of_partition_key=st.session_state.user_id,
            #TODO ์ „์ฒด ๋ณด์—ฌ์ค„ ๊ฐœ์ˆ˜ ์„ค์ •
            limit_num=10
        )

    if not debate_history:
        st.info('There is no previous debate history', icon="โ„น๏ธ")

    print(debate_history)

    _, _, pre, home  = st.columns([5, 5, 1, 1])
    with pre:
        st.button("๐Ÿ”™", on_click=page_1_2_controller, use_container_width=True)
    with home:
        st.button("๐Ÿ”", on_click=page_n_1_controller, use_container_width=True)
    st.header("Debate History")

    st.button(
        label=f'๐Ÿš€ Start new debate',
        type='primary',
        on_click=page_3_4_controller
    )
    st.write("_"*50)

    num_history = len(debate_history)
    for i in range(num_history):
        with st.container():
            st.write(f"#### {i + 1}")
            st.write(f"Debate Thema : {debate_history[i]['debate_theme']}")
            st.write(f"Debate Topic : {debate_history[i]['debate_topic']}")
            st.write(f"Case 1 : {debate_history[i]['case1']}")
            st.write(f"Case 2 : {debate_history[i]['case2']}")
            st.write(f"Case 3 : {debate_history[i]['case3']}")
            st.write(f"Created at : {debate_history[i]['time_stamp']}")
            st.button(
                label='Continue this dabate',
                key=str(i),
                on_click=page_4_5_controller
            )
            st.write("_"*50)

#########################################################
# Page 4
#########################################################
def page4():
    #########################################################
    # Tab 1 - Total Debate (ํ† ๋ก  ์ค€๋น„ -> ์—ฐ์Šต -> ํ‰๊ฐ€)
    #########################################################

    _, _, pre, home  = st.columns([5, 5, 1, 1])
    with pre:
        st.button("๐Ÿ”™", on_click=page_2_3_controller, use_container_width=True)
    with home:
        st.button("๐Ÿ”", on_click=page_n_1_controller, use_container_width=True)

    st.header("Total Debate")
    debate_themes = ['Education','Sports','Religion','Justice','Pandemic','Politics','Minority','etc']

    st.subheader("1. Theme")
    st.session_state.debate_theme = st.selectbox("Choose your debate theme", debate_themes)

    if st.session_state.debate_theme == 'Education':
        topic_list = [
            "THBT college entrance examinations should accept students only on the basis of their academic performance in secondary education.", 
            "THS a world where the government gives cash that individuals can use to freely select their academic preference (including but not limited to school of choice, private academies, and tutoring) instead of funding for public education.",
            "THW abolish all requirements and evaluation criteria in higher education (i.e., attendance, exams, assignments)."
            ]
    elif st.session_state.debate_theme == 'Sports':
        topic_list = [
            "THBT having star players for team sports do more harm than good to the team.",
            "THR the emphasis on winning a medal in the Olympics as a core symbol of success.",
            "THP a world where sports serves purely entertainment purposes even at the expense of fair play."
            ]
    elif st.session_state.debate_theme == 'Religion':
        topic_list = [
            "THW, as a religious group/leader, cease attempts at increasing the number of believers and instead prioritize boosting loyalty amongst adherents to the religion.",
            "Assuming feasibility, TH prefers a world where a panel of church leaders would create a universally accepted interpretation of the Bible that the believers would abide by.",
            "THW aggressively crackdown on megachurches."
            ]
    elif st.session_state.debate_theme == 'Justice':
        topic_list = [
            "In 2050, AI robots are able to replicate the appearance, conversation, and reaction to emotions of human beings. However, their intelligence still does not allow them to sense emotions and feelings such as pain, happiness, joy, and etc.",
            "In the case a human destroys the robot beyond repair, THW charge murder instead of property damage.",
            "THP a world where the criminal justice systemโ€™s role is mainly for victimโ€™s vengeance. THW allow prosecutors and victims to veto assigned judges."
            ]
    elif st.session_state.debate_theme == 'Pandemic':
        topic_list = [
            "During a pandemic, THBT businesses that benefit from the pandemic should be additionally taxed.",
            "THW nullify the effect of medical patents in cases of medical emergencies.",
            "THW ban media content that denies the efficacy of the COVID-19 without substantial evidence."
            ]
    elif st.session_state.debate_theme == 'Politics':
        topic_list = [
            "Info: The Candle Light Will (์ด›๋ถˆ๋ฏผ์‹ฌ) is a term derived from the symbolic candle-light protests for the impeachment of the late president Park Geun Hye, commonly used to mean the peopleโ€™s will to fight against corrupt governments. The Moon administration has frequently referred to the Candle Light Will as the driving force behind its election that grants legitimacy to its policies. THR the โ€˜candle light willโ€™ narrative in the political discourse of South Korea.",
            "THW impose a cap on the property and income of politicians.",
            "THW give the youth extra votes."
            ]
    elif st.session_state.debate_theme == 'Minority':
        topic_list = [
            "Context: A prominent member of the LGBT movement has discovered that a very influential politician helping the LGBT movement has been lying about their sexual orientation as being gay when they are straight. THW disclose this information.",
            "THBT the LGBTQIA+ movement should denounce the existence of marriage as opposed to fighting for equal marriage rights.",
            "THBT the LGBTQIA+ movement should condemn the consumption of movies and TV shows that cast straight actors/actresses in non-heterosexual identified roles."
            ]
    else:
        topic_list = [
            "THW remove all laws that relate to filial responsibilities.",
            "THW require parents to receive approval from experts in relevant fields before making crucial decisions for their children.",
            "Assuming it is possible to measure the โ€˜societal dangerโ€™ of the fetus in the future, THBT the state should raise infants that pose high levels of threat.",
            "THBT any upper limits on prison sentences for particularly heinous crimes should be abolished.",
            "THW require dating apps to anonymize profile pictures.",
            "THW adopt a Pass/Fail grading system for students who suffer from mental health problems (e.g. depression, bipolar disorder, etc.).",
            "THBT South Korean feminist movements should reject feminist icons that are adversarial and embody violence.",
            "THBT freedom of speech should be considered obsolete.",
            "THR the narrative that eccentric personalities are essential to create art.",
            "THW allow parents of severely mentally disabled children to medically impede their children's physical growth.",
            "THR the emphasis on longevity in relationships.",
            "Assuming feasibility, THW choose to continuously relive the happiest moment of oneโ€™s life."
            ]

    st.subheader("2. Topic")
    topic = st.session_state.topic = st.selectbox(
        label="Choose your topic",
        options=topic_list,
        format_func=lambda x: x[:45] + "...",
        # help="This is help message",
    )
    st.write("> Topic : ", topic)

    st.subheader("3. Side")
    st.session_state.pros_and_cons = st.selectbox("Choose your Side (Pros and Cons)", ["Pros", "Cons"])

    st.subheader("4. Cases")
    st.caption('๐Ÿ“ข These are just a tool to help you structure your thoughts on the content and does not reflect the actual discussion.')

    #########################################################
    # Case๋„ ์„ธ์…˜์— ์ €์žฅ
    #########################################################
    st.session_state.case1 = st.text_area(
        label="Write a Case 1",
        placeholder="Each case should be consisted of opinion, reasoning, and example.",
        height=150
        )
    st.session_state.case2 = st.text_area(
        label="Write a Case 2",
        placeholder="Each case should be consisted of opinion, reasoning, and example.",
        height=150
    )
    st.session_state.case3 = st.text_area(
        label="Write a Case 3",
        placeholder="Each case should be consisted of opinion, reasoning, and example.",
        height=150
    )
    case_error_message = st.empty()
    
    st.write("*" * 50)

    # Save the data to database
    start = st.button(
        label="Start Debate",
        on_click=put_item(
            table=dynamodb.Table('DEBO_debate_setting'),
            item={
                'user_id': st.session_state.user_id,
                'time_stamp': time_stamp,
                'debate_theme': st.session_state.debate_theme,
                'debate_topic': st.session_state.topic,
                'case1': st.session_state.case1,
                'case2': st.session_state.case2,
                'case3': st.session_state.case3,
                'session_num': st.session_state.session_num,
            }
            )
        )

    def validate_case(error_message):
        if not st.session_state.case1 or not st.session_state.case2 or not st.session_state.case3:
            case_error_message.error("Please fill out above all", icon="๐Ÿšจ")
            return False
        else:
            # st.session_state.case1 = st.session_statecase1
            # st.session_state.case2 = st.session_statecase2
            # st.session_state.case3 = st.session_statecase3
            return True

    if start:
        if validate_case(case_error_message):
            page_4_5_controller()
            st.experimental_rerun()

    #########################################################
    # Ask to GPT
    #########################################################
    with st.sidebar:
        st.sidebar.title('Ask to GPT')
        user_input = st.sidebar.text_area(
            label="Question", 
            placeholder="Input text here",
            height=100)
        output = st.sidebar.button("Ask")
        error_message = st.empty()
        if output:
            if not user_input:
                error_message.error("Please enter your question")
                result = ""
            else:
                try:
                    result = gpt_call(user_input)
                except:
                    error_message.error("Chat-GPT Error : The engine is currently overloaded, it will be auto-reloaded in a second")
                    time.sleep(0.5)
                    st.experimental_rerun()

                # save user_prompt and bot_response to database
                put_item(
                    table=dynamodb.Table('DEBO_gpt_ask'),
                    item={
                        'user_id': st.session_state.user_id,
                        'time_stamp': time_stamp,
                        'user_prompt': user_input,
                        'bot_response': result,
                        'session_num': st.session_state.session_num,
                    }
                )

        else:
            result = ""

        st.sidebar.text_area(
            label="Answer", 
            placeholder="(Answer will be shown here)",
            value=result,
            height=400)

#########################################################
# Page5
#########################################################

def generate_response(prompt):

    st.session_state['user_debate_history'].append(prompt)
    st.session_state['total_debate_history'].append({"role": "user", "content": prompt})

    if len(prompt.split()) < 10:
        response = "Please speak longer!"
    else:
        response = gpt_call_context(st.session_state['total_debate_history'])
    
    st.session_state['bot_debate_history'].append(response)
    st.session_state['total_debate_history'].append({"role": "assistant", "content": response})
    return response

def execute_stt(audio, error_message):

    # audio ๊ธฐ๋ก ๋ˆ„์ 
    #user_audio_path = "audio/" + str(st.session_state.user_id) + "_" + str(st.session_state.session_num) + "_" + str(time.time()) + ".wav"
    # audio ๊ธฐ๋ก์„ ๋ˆ„์ ํ•˜๊ณ  ์‹ถ์ง€ ์•Š๋‹ค๋ฉด
    user_audio_path = "audio/audio.wav"

    wav_file = open(user_audio_path, "wb")
    wav_file.write(audio.tobytes())

    try:
        user_input = whisper_transcribe(wav_file)
    except:
        error_message.error("Whisper Error : The engine is currently overloaded, it will be auto-reloaded in a second")
        time.sleep(1)
        st.experimental_rerun()

    # close file
    wav_file.close()

    return user_input

def page5():

    # time
    st.session_state.start_time = time.time()

    #########################################################
    # Ask to GPT
    #########################################################
    with st.sidebar:
        st.sidebar.title('Ask to GPT')
        user_input = st.sidebar.text_area(
            label="Question", 
            placeholder="Input text here",
            height=100)
        output = st.sidebar.button("Ask")
        error_message = st.empty()
        if output:
            if not user_input:
                error_message.error("Please enter your question")
                result = ""
            else:
                try:
                    result = gpt_call(user_input)
                except:
                    error_message.error("Chat-GPT Error : The engine is currently overloaded, it will be auto-reloaded in a second")
                    time.sleep(0.5)
                    st.experimental_rerun()
                
                put_item(
                    table=dynamodb.Table('DEBO_gpt_ask'),
                    item={
                        'user_id': st.session_state.user_id,
                        'time_stamp': time_stamp,
                        'user_prompt': user_input,
                        'bot_response': result,
                        'session_num': st.session_state.session_num,
                    }
                )
        else:
            result = ""

        st.sidebar.text_area(
            label="Answer", 
            placeholder="(Answer will be shown here)",
            value=result,
            height=400)

    # Chat-GPT api error handling
    gpt_error_top = st.empty()

    # default system prompt settings
    if not st.session_state['total_debate_history']:

        # bot role, pros and cons
        if st.session_state['pros_and_cons'] == "Pros":
            bot_role = "Cons"
        else:
            bot_role = "Pros"

        debate_preset = "\n".join([
            "Debate Rules: ",
            "1) This debate will be divided into two teams, pro and con, with two debates on each team.",
            "2) The order of speaking is: first debater for the pro side, first debater for the con side, second debater for the pro side, second debater for the con side.",
            "3) Answer logically with an introduction, body, and conclusion.",
            "4) Your role : " + bot_role + " side debator",
            "5) Debate subject: " + st.session_state['topic'],
        ])
        first_prompt = "Now we're going to start. Summarize the subject and your role. And ask user ready to begin."

        st.session_state['total_debate_history'] = [
            {"role": "system", "content": debate_preset}
        ]
        try:
            response = gpt_call(debate_preset + "\n" + first_prompt, role="system")
        except:
            gpt_error_top.error("Chat-GPT Error : The engine is currently overloaded, it will be auto-reloaded in a second")
            time.sleep(1)
            st.experimental_rerun()
            
        st.session_state['total_debate_history'].append({"role": "assistant", "content": response})
        st.session_state['bot_debate_history'].append(response)

    _, _, pre, home  = st.columns([5, 5, 1, 1])
    with pre:
        st.button("๐Ÿ”™", on_click=page_3_4_controller, use_container_width=True)
    with home:
        st.button("๐Ÿ”", on_click=page_n_1_controller, use_container_width=True)

    # container for chat history
    response_container = st.container()
    # Chat-GPT & Whisper api error handling
    openai_error_bottom = st.empty()
    # container for text box
    container = st.container()
    reload = False

    with container:
        with st.form(key='my_form', clear_on_submit=True):
            user_input = None
            # record voice
            audio = audiorecorder("โบ๏ธ Click to record", "โน๏ธ Recording...")
            if np.array_equal(st.session_state['pre_audio'], audio):
                audio = np.array([])

            #user_input = st.text_area("You:", key='input', height=100)
            submit_buttom = st.form_submit_button(label='๐Ÿ’ฌ Send')
            send_error_message = st.empty()
        
        #if submit_buttom and user_input:
        if submit_buttom:
            if audio.any():
                user_input = execute_stt(audio, openai_error_bottom)

                try :
                    response = generate_response(user_input)
                    print("response", response)
                except:
                    openai_error_bottom.error("Chat-GPT Error : The engine is currently overloaded, it will be auto-reloaded in a second")
                    time.sleep(1)
                    st.experimental_rerun()
                st.session_state['pre_audio'] = audio

                debate_main_latest_data = get_lastest_item(
                    table=dynamodb.Table('DEBO_debate_main'),
                    name_of_partition_key="user_id",
                    value_of_partition_key=st.session_state.user_id,
                    limit_num=1
                )

                print(f'debate_main_latest_data : {debate_main_latest_data}')
                if not debate_main_latest_data:
                    turn_num = 0
                else:
                    turn_num = debate_main_latest_data[0]['turn_num']

                put_item(
                    table=dynamodb.Table('DEBO_debate_main'),
                    item={
                        'user_id': st.session_state.user_id,
                        'time_stamp': time_stamp,
                        'session_num': st.session_state.session_num,
                        'bot_response': response,
                        'user_prompt': user_input,
                        'turn_num': turn_num,
                    }
                )
            else:
                send_error_message.error("Please record your voice first", icon="๐Ÿšจ")
                reload = True

    with response_container:
        message(st.session_state['bot_debate_history'][0], key='0_bot')
        if len(st.session_state['bot_debate_history']) == 1:
            text_to_speech = gTTS(text=st.session_state['bot_debate_history'][0], lang='en', slow=False)
            text_to_speech.save(f"audio/bot_{st.session_state['session_num']}_res_0.mp3")
        
        audio_file = open(f"audio/bot_{st.session_state['session_num']}_res_0.mp3", 'rb')
        audio_bytes = audio_file.read()
        st.audio(audio_bytes, format='audio/ogg')

        for i in range(len(st.session_state['user_debate_history'])):
            message(st.session_state['user_debate_history'][i], is_user=True, key=str(i)+'_user')
            message(st.session_state['bot_debate_history'][i + 1], key=str(i + 1)+'_bot')
            if i == len(st.session_state['bot_debate_history']) - 2 and not reload:
                text_to_speech = gTTS(text=st.session_state['bot_debate_history'][i + 1], lang='en', slow=False)
                text_to_speech.save(f"audio/bot_{st.session_state['session_num']}_res_{str(i + 1)}.mp3")
            audio_file = open(f"audio/bot_{st.session_state['session_num']}_res_{str(i + 1)}.mp3", 'rb')
            audio_bytes = audio_file.read()
            st.audio(audio_bytes, format='audio/ogg')
        reload = False

    st.button(
        label="Next",
        type="primary",
        on_click=page_5_6_controller
    )

print("#"*80)
pprint.pprint(st.session_state.to_dict())
print("#"*80)

#########################################################
# Page6 - Total Debate Evaluation
#########################################################
def page6():

    # end time
    st.session_state.end_time = time.time()
    st.session_state.debate_time = st.session_state.end_time - st.session_state.start_time

    _, _, pre, home  = st.columns([5, 5, 1, 1])
    with pre:
        st.button("๐Ÿ”™", on_click=page_4_5_controller, use_container_width=True)
    with home:
        st.button("๐Ÿ”", on_click=page_n_1_controller, use_container_width=True)

    # st.tab
    st.header('Total Debate Evaluation')

    st.write('Note that evaluation using GPT is an experimental feature. Please check it out and give us your feedback.')

    tab1, tab2, tab3 = st.tabs(['Debate Evaluation', 'Perfect Case', 'Debate Analysis'])

    with tab1:
        st.header("Debate Evaluation")

        # ์ „์ฒด, ์œ ์ €, ๋ด‡ ์„ธ ๊ฐ€์ง€ ์˜ต์…˜ ์ค‘์— ์„ ํƒ
        #judgement_who = st.selectbox("Choose what you want! (Evaluation result / Perfect case on this theme)", debate_themes)

        if st.session_state.judgement_result == "":
            with st.spinner('Wait for judgement result...'):
                judgement_result = ""

                user_debate_history = "".join(
                    st.session_state.user_debate_history
                )
                bot_debate_history = "".join(
                    st.session_state.bot_debate_history
                )

                judgement_result = debate_judgement(
                    user_debate_history, 
                    bot_debate_history
                    )

                st.write("Debate Judgement Result")
                st.write(judgement_result)

                if judgement_result != "":
                    put_item(
                        table=dynamodb.Table('DEBO_evaluation'),
                        item={
                            'user_id': st.session_state.user_id,
                            'time_stamp': time_stamp,
                            'judgement_text': judgement_result,
                            'session_num': st.session_state.session_num,
                        }
                    )
            st.success('Done!')
        else:
            st.write(st.session_state.judgement_result)

    with tab2:
        st.header("Perfect Case")

        perfect_case = perfect_case_selector(
            st.session_state.debate_theme, 
            st.session_state.topic
            )

        st.write(perfect_case)


    with tab3:
        st.header('Debate Analysis')

        # ์œ ์ €์˜ history๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋ฐœํ™”๋Ÿ‰, ๋นˆ์ถœ ๋‹จ์–ด, ๋ฐœํ™” ์Šต๊ด€ ์„ธ ๊ฐ€์ง€๋ฅผ ๋ถ„์„
        user_history = st.session_state.user_debate_history

        # 1. ๋ฐœํ™”๋Ÿ‰: ์ด ๋‹จ์–ด, ํ‰๊ท  ์†๋„(๋‹จ์–ด/์‹œ๊ฐ„)๋ฅผ ํ‰๊ท  ๋ฐœํ™”๋Ÿ‰ ํ˜น์€ ์ฐธ๊ณ  ์ง€ํ‘œ์™€ ๋น„๊ตํ•ด ์ œ์‹œ

        # ์ด ๋‹จ์–ด
        # ํ…์ŠคํŠธ๋ฅผ ๋‹จ์–ด๋กœ ๋ถ„ํ• ํ•ฉ๋‹ˆ๋‹ค.
        # ๊ฐ ๋‹จ์–ด์˜ ๋นˆ๋„๋ฅผ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค.

        # ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•˜๊ณ , ๊ณต๋ฐฑ์„ ๊ธฐ์ค€์œผ๋กœ ๋‹จ์–ด๋ฅผ ๋ถ„ํ• ํ•ฉ๋‹ˆ๋‹ค.
        total_word_list = "".join(user_history).split()
        total_word_count = len(total_word_list)
        #total_word_count = len(user_history.split())
        st.write("Total Word Count: ", total_word_count)

        # ํ‰๊ท  ์†๋„(๋‹จ์–ด/์‹œ๊ฐ„)
        #user_debate_time = st.session_state.user_debate_time
        average_word_per_time = total_word_count / st.session_state.debate_time # ์‹œ๊ฐ„ ๋‹จ์œ„๋ณด๊ณ  ๋‚˜์ค‘์— ์ˆ˜์ •ํ•˜๊ธฐ
        st.write("Average Word Per Time: ", average_word_per_time)

        # 2. ๋นˆ์ถœ ๋‹จ์–ด: ๋ฐ˜๋ณตํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” ๋‹จ์–ด ๋ฆฌ์ŠคํŠธ
        # ๋นˆ๋„ ๊ณ„์‚ฐ
        frequency = Counter(total_word_list)
        # ๊ฐ€์žฅ ๋นˆ๋„๊ฐ€ ๋†’์€ ๋ฐ์ดํ„ฐ ์ถœ๋ ฅ
        most_common_data = frequency.most_common(5)

        st.write("Most Common Words: ")
        for word, count in most_common_data:
            st.write(" - ", word, ":", count)

        # print(most_common_data)
        # st.write("Most Common Words: ", most_common_data)

        # 3. ๋ฐœํ™” ์Šต๊ด€: ๋ถˆํ•„์š”ํ•œ ์–ธ์–ด์Šต๊ด€(์•„, ์Œ)
        # whisper preprocesser์—์„œ ์ฃผ๋ฉด
        disfluency_word_list = ['eh', 'umm', 'ah', 'uh', 'er', 'erm', 'err']
        # Count the disfluency words
        disfluency_counts = sum(user_word in disfluency_word_list for user_word in user_history)
        st.write("Disfluency Counts: ", disfluency_counts)

        if total_word_count != "" and average_word_per_time != "" and disfluency_counts != "":

                put_item(
                    table=dynamodb.Table('DEBO_debate_analysis'),
                    item={
                        'user_id': st.session_state.user_id,
                        'time_stamp': time_stamp,
                        'total_word_count': total_word_count,
                        'average_word_per_time': Decimal(str(average_word_per_time)),
                        'disfluency_counts': disfluency_counts,
                        'session_num': int(st.session_state.session_num),
                    }
                )

        # ์œ ์ €์™€ ๋ด‡์˜ ๋Œ€ํ™” ๋ฐ์ดํ„ฐ๊ฐ€ ์„ธ์…˜์— ๋‚จ์•„์žˆ์Œ
        # st.session_state.debate_history
    

#########################################################
# Page7
#########################################################

def page7():

    # end time
    st.session_state.end_time = time.time()
    st.session_state.debate_time = st.session_state.end_time - st.session_state.start_time

    _, _, pre, home  = st.columns([5, 5, 1, 1])
    with pre:   
        st.button("๐Ÿ”™", on_click=page_1_2_controller, use_container_width=True)
    with home:
        st.button("๐Ÿ”", on_click=page_n_1_controller, use_container_width=True)

    st.header('Total Debate Evaluation')

    tab1, tab2 = st.tabs(['Debate Judgement', 'Debate Analysis'])

    with tab1:
        st.header("Debate Evaluation")
        
        debate_themes = ['User-Bot', "User", "Bot"]

        # ์ „์ฒด, ์œ ์ €, ๋ด‡ ์„ธ ๊ฐ€์ง€ ์˜ต์…˜ ์ค‘์— ์„ ํƒ
        judgement_who = st.selectbox("Choose your debate theme", debate_themes)

        if st.session_state.judgement_result == "":
            with st.spinner('Wait for judgement result...'):
                judgement_result = ""

                user_debate_history = "".join(
                    st.session_state.user_debate_history
                )
                bot_debate_history = "".join(
                    st.session_state.bot_debate_history
                )

                judgement_result = debate_judgement(
                    judgement_who, 
                    user_debate_history, 
                    bot_debate_history
                    )
                
                st.session_state.judgement_result = judgement_result
                
                st.write("Debate Judgement Result")
                st.write(judgement_result)

                if judgement_result:
                        put_item(
                            table=dynamodb.Table('DEBO_evaluation'),
                            item={
                                'user_id': st.session_state.user_id,
                                'time_stamp': time_stamp,
                                'judgement_text': judgement_result,
                                'session_num': int(st.session_state.session_num),
                            }
                        )
                st.success('Done!')
        else:
            st.write(st.session_state.judgement_result)

    with tab2:
        st.header('Debate Analysis')

        # ์œ ์ €์˜ history๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋ฐœํ™”๋Ÿ‰, ๋นˆ์ถœ ๋‹จ์–ด, ๋ฐœํ™” ์Šต๊ด€ ์„ธ ๊ฐ€์ง€๋ฅผ ๋ถ„์„
        user_history = st.session_state.user_debate_history

        # 1. ๋ฐœํ™”๋Ÿ‰: ์ด ๋‹จ์–ด, ํ‰๊ท  ์†๋„(๋‹จ์–ด/์‹œ๊ฐ„)๋ฅผ ํ‰๊ท  ๋ฐœํ™”๋Ÿ‰ ํ˜น์€ ์ฐธ๊ณ  ์ง€ํ‘œ์™€ ๋น„๊ตํ•ด ์ œ์‹œ

        # ์ด ๋‹จ์–ด
        # ํ…์ŠคํŠธ๋ฅผ ๋‹จ์–ด๋กœ ๋ถ„ํ• ํ•ฉ๋‹ˆ๋‹ค.
        # ๊ฐ ๋‹จ์–ด์˜ ๋นˆ๋„๋ฅผ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค.
        total_word_count = len(user_history)
        #total_word_count = len(user_history.split())
        st.write("Total Word Count: ", total_word_count)

        # ํ‰๊ท  ์†๋„(๋‹จ์–ด/์‹œ๊ฐ„)
        #user_debate_time = st.session_state.user_debate_time
        average_word_per_time = total_word_count / st.session_state.debate_time # ์‹œ๊ฐ„ ๋‹จ์œ„๋ณด๊ณ  ๋‚˜์ค‘์— ์ˆ˜์ •ํ•˜๊ธฐ
        st.write("Average Word Per Time: ", average_word_per_time)

        # 2. ๋นˆ์ถœ ๋‹จ์–ด: ๋ฐ˜๋ณตํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” ๋‹จ์–ด ๋ฆฌ์ŠคํŠธ
        # ๋นˆ๋„ ๊ณ„์‚ฐ
        frequency = Counter(user_history)
        # ๊ฐ€์žฅ ๋นˆ๋„๊ฐ€ ๋†’์€ ๋ฐ์ดํ„ฐ ์ถœ๋ ฅ
        most_common_data = frequency.most_common(10)
        print(most_common_data)
        st.write("Most Common Words: ", most_common_data)

        # 3. ๋ฐœํ™” ์Šต๊ด€: ๋ถˆํ•„์š”ํ•œ ์–ธ์–ด์Šต๊ด€(์•„, ์Œ)
        # whisper preprocesser์—์„œ ์ฃผ๋ฉด
        disfluency_word_list = ['eh', 'umm', 'ah', 'uh', 'er', 'erm', 'err']
        # Count the disfluency words
        disfluency_counts = sum(user_word in disfluency_word_list for user_word in user_history)
        st.write("Disfluency Counts: ", disfluency_counts)

        if total_word_count != "" and average_word_per_time != "" and disfluency_counts != "":
                put_item(
                    table=dynamodb.Table('DEBO_evaluation'),
                    item={
                        'user_id': st.session_state.user_id,
                        'time_stamp': time_stamp,
                        'total_word_count': total_word_count,
                        'average_word_per_time': Decimal(str(average_word_per_time)),
                        'disfluency_counts': disfluency_counts,
                        'session_num': int(st.session_state.session_num),
                    }
                )

        # ์œ ์ €์™€ ๋ด‡์˜ ๋Œ€ํ™” ๋ฐ์ดํ„ฐ๊ฐ€ ์„ธ์…˜์— ๋‚จ์•„์žˆ์Œ
        # st.session_state.debate_history

    ############################################
    # Visualization
    ############################################

    # ์ด์ „์— ๊ธฐ๋ก๋œ ๊ฐ’์ด ์žˆ๋‹ค๋ฉด, ๊ทธ๋ž˜ํ”„๋ฅผ ๊ทธ๋ฆฝ๋‹ˆ๋‹ค.
    # ์ด์ „์— ๊ธฐ๋ก๋œ ๊ฐ’์ด ์—†๋‹ค๋ฉด, ๊ทธ๋ž˜ํ”„๋ฅผ ๊ทธ๋ฆฌ์ง€ ์•Š์Šต๋‹ˆ๋‹ค.


#########################################################
# Page Routing
#########################################################
pages = {
    "Page 1": page1, # user_id๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š” ํŽ˜์ด์ง€
    "Page 2": page2, # ์›ํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์„ ํƒํ•˜๋Š” ํŽ˜์ด์ง€
    "Page 3": page3, # ๊ณผ๊ฑฐ ํ† ๋ก  ๋‚ด์—ญ์„ ์„ ํƒํ•˜๋Š” ํŽ˜์ด์ง€
    "Page 4": page4, # ํ† ๋ก  ์„ธ๋ถ€์‚ฌํ•ญ ์„ค์ •
    "Page 5": page5, # Total Debate
    "Page 6": page6, # Evaluation Only
    "Page 7": page7, # Analyzing Utterances
}

selection = st.session_state.page
print("selection:", selection)

page = pages[selection]
# Execute selected page function
page()