codingchild commited on
Commit
1a7b403
1 Parent(s): 761512c
Files changed (3) hide show
  1. app.py +560 -168
  2. vocal_app.py +0 -631
  3. vocal_app.sh +0 -1
app.py CHANGED
@@ -1,147 +1,245 @@
1
-
2
  import streamlit as st
 
 
 
 
 
3
  from streamlit_chat import message
4
 
5
- # modules
6
- from modules.db_modules import get_db
7
- from modules.db_modules import get_lastest_item
8
- from modules.query_modules import query
9
 
 
 
 
 
 
10
 
11
- #############################################
12
- # DB connection
13
- #############################################
14
- dynamodb = get_db()
15
- debate_bot_log_table = dynamodb.Table('debate_bot_log')
16
 
 
 
17
 
18
- #############################################
19
- # Streamlit setting
20
- #############################################
21
- st.header("DEBATE BOT")
22
- st.text("If you want to reset your session, refresh the page.")
23
 
24
- if 'generated' not in st.session_state:
25
- st.session_state['generated'] = []
26
 
27
- if 'past' not in st.session_state:
28
- st.session_state['past'] = []
29
 
 
 
 
30
 
31
- #############################################
32
- # Setting Form
33
- #############################################
34
 
35
- if 'user_id' not in st.session_state:
36
  st.session_state.user_id = ""
37
 
38
- if 'debate_topic' not in st.session_state:
39
- st.session_state.debate_topic = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- if 'session_num' not in st.session_state:
42
- st.session_state.session_num = 0
43
 
44
- if 'session_history_exist' not in st.session_state:
45
- st.session_state.history_exist = False
 
 
 
 
46
 
47
- if 'debate_subject' not in st.session_state:
48
- st.session_state.debate_subject = ""
 
49
 
 
 
50
 
51
- def form_callback(history_exist):
 
52
 
53
- # 과거 히스토리가 없다면, 세션 넘버를 0으로 초기화
54
- if history_exist == False:
55
- st.session_state.session_num = 0
56
- # 과거 히스토리가 있다면, 유저의 데이터에서 session_num을 가져와서 사용함
 
57
  else:
58
- # 만약 session_state 이전 대화 기록이 없다면, session_num에 1을 추가해서 업데이트함
59
- if st.session_state.past == []:
60
- st.session_state.session_num += 1
61
- # 만약 session_state 이전 대화 기록이 있다면, 업데이트가 필요없으므로 session_num을 업데이트하지 않으
62
- else:
63
- st.session_state.session_num = st.session_state.session_num
64
- #st.experimental_rerun()
65
 
66
- print("st.session_state.session_num(form_callback)", st.session_state.session_num)
 
67
 
 
 
68
 
69
- with st.form("first_form"):
 
70
 
71
- #############################################
72
- # User id
73
- #############################################
74
 
75
- user_id = ""
 
 
 
76
 
77
- user_id = st.text_input(
78
- "Enter Your User ID",
79
- st.session_state.user_id, # For remain the id
80
- key='user_id'
 
 
 
 
81
  )
82
-
83
- #############################################
84
- # Debate Theme
85
- #############################################
86
- debate_theme =st.selectbox(label='Debate Theme', options=[
87
- 'Education',
88
- 'Sports',
89
- 'Religion',
90
- 'Justice',
91
- 'Pandemic',
92
- 'Politics',
93
- 'Minority',
94
- 'etc'
95
- ])
96
- change = st.form_submit_button("Change")
97
-
98
- #############################################
99
- # Debate Topic
100
- #############################################
101
- if debate_theme == "Education":
102
- topic_list = (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  "THBT college entrance examinations should accept students only on the basis of their academic performance in secondary education.",
104
  "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.",
105
  "THW abolish all requirements and evaluation criteria in higher education (i.e., attendance, exams, assignments)."
106
- )
107
- elif debate_theme == "Sports":
108
- topic_list = (
 
109
  "THBT having star players for team sports do more harm than good to the team.",
110
  "THR the emphasis on winning a medal in the Olympics as a core symbol of success.",
111
  "THP a world where sports serves purely entertainment purposes even at the expense of fair play."
112
- )
113
- elif debate_theme == "Religion":
114
- topic_list = (
 
115
  "THW, as a religious group/leader, cease attempts at increasing the number of believers and instead prioritize boosting loyalty amongst adherents to the religion.",
116
  "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.",
117
  "THW aggressively crackdown on megachurches."
118
- )
119
- elif debate_theme == "Justice":
120
- topic_list = (
 
121
  "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.",
122
  "In the case a human destroys the robot beyond repair, THW charge murder instead of property damage.",
123
  "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."
124
- )
125
- elif debate_theme == "Pandemic":
126
- topic_list = (
 
127
  "During a pandemic, THBT businesses that benefit from the pandemic should be additionally taxed.",
128
  "THW nullify the effect of medical patents in cases of medical emergencies.",
129
  "THW ban media content that denies the efficacy of the COVID-19 without substantial evidence."
130
- )
131
- elif debate_theme == "Politics":
132
- topic_list = (
 
133
  "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.",
134
  "THW impose a cap on the property and income of politicians.",
135
  "THW give the youth extra votes."
136
- )
137
- elif debate_theme == "Minority":
138
- topic_list = (
 
139
  "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.",
140
  "THBT the LGBTQIA+ movement should denounce the existence of marriage as opposed to fighting for equal marriage rights.",
141
  "THBT the LGBTQIA+ movement should condemn the consumption of movies and TV shows that cast straight actors/actresses in non-heterosexual identified roles."
142
- )
 
143
  else:
144
- topic_list = (
145
  "THW remove all laws that relate to filial responsibilities.",
146
  "THW require parents to receive approval from experts in relevant fields before making crucial decisions for their children.",
147
  "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.",
@@ -154,89 +252,383 @@ with st.form("first_form"):
154
  "THW allow parents of severely mentally disabled children to medically impede their children's physical growth.",
155
  "THR the emphasis on longevity in relationships.",
156
  "Assuming feasibility, THW choose to continuously relive the happiest moment of one’s life."
157
- )
158
 
159
- debate_topic = st.selectbox(
160
- '2. Choose your Topic',
161
- topic_list
162
- )
163
-
164
- #############################################
165
- # Role of Bot
166
- #############################################
167
- bot_role_list = (
168
- "주제 정의",
169
- "POI 연습",
170
- "역할 추천",
171
- "주장 비판",
172
- "토론"
173
- )
174
 
175
- bot_role = st.selectbox(
176
- '3. Choose Role of Bot',
177
- bot_role_list
178
- )
179
 
180
- # # user_id가 있는 경우
181
- if user_id != "":
182
- # user의 id에서 가장 최신 데이터 1개만 쿼리함
183
- item = get_lastest_item(
184
- table=debate_bot_log_table,
185
- name_of_partition_key='user_id',
186
- value_of_partition_key=user_id,
187
- limit_num=1
188
  )
189
- print("item", item)
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
- # 처음 들어온 유저라면
192
- if item == []:
193
- st.session_state.history_exist = False
194
- # 이미 데이터가 있는 유저라면, session_num에 1을 추가하기(갱신)
195
  else:
196
- st.session_state.history_exist = True
197
- st.session_state.session_num = item[0]['session_num']
198
- else:
199
- print("User_name을 입력해주세요.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
- #############################################
202
- # User input
203
- #############################################
204
- user_input = st.text_input(
205
- 'Message',
206
- '',
207
- key='input'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
  )
209
- form_submitted = st.form_submit_button(
210
- 'Send',
211
- on_click=form_callback(st.session_state.history_exist)
212
  )
213
 
214
- #############################################
215
- # Query
216
- #############################################
217
- if form_submitted and user_input:
218
-
219
- output = query(
220
- db_table=debate_bot_log_table,
221
- user_id=user_id,
222
- prompt=user_input,
223
- debate_subject=debate_topic,
224
- bot_role=bot_role,
225
- session_num=st.session_state.session_num
226
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
 
228
- st.session_state.past.append(user_input)
229
- st.session_state.generated.append(output)
230
 
231
- if st.session_state['generated']:
232
- for i in range(len(st.session_state['generated'])-1, -1, -1):
233
- message(
234
- st.session_state['past'][i],
235
- is_user=True,
236
- key=str(i) + '_user'
237
- )
238
- message(
239
- st.session_state["generated"][i],
240
- key=str(i),
241
- #avatar_style="Fun Emoji"
242
- )
 
 
1
  import streamlit as st
2
+ import numpy as np
3
+ import openai
4
+
5
+ from gtts import gTTS
6
+ from collections import Counter
7
  from streamlit_chat import message
8
 
9
+ from dotenv import dotenv_values
10
+ from bots.judgement_bot import debate_judgement
11
+ from collections import Counter
12
+ import time
13
 
14
+ from audiorecorder import audiorecorder
15
+
16
+ # modules
17
+ from modules.gpt_modules import gpt_call, gpt_call_context
18
+ #from modules.whisper_modules import transcribe
19
 
20
+ config = dotenv_values(".env")
 
 
 
 
21
 
22
+ openai.organization = config.get('OPENAI_ORGANIZATION')
23
+ openai.api_key = config.get('OPENAI_API_KEY')
24
 
25
+ #openai.organization = st.secrets['OPENAI_ORGANIZATION']
26
+ #openai.api_key = st.secrets['OPENAI_API_KEY']
 
 
 
27
 
 
 
28
 
29
+ # Page Configuration
30
+ st.set_page_config(page_title="Streamlit App")
31
 
32
+ # Initialize session state variables
33
+ if "page" not in st.session_state:
34
+ st.session_state.page = "Page 1"
35
 
36
+ if "topic" not in st.session_state:
37
+ st.session_state.topic = "None"
 
38
 
39
+ if "user_id" not in st.session_state:
40
  st.session_state.user_id = ""
41
 
42
+ if "openAI_token" not in st.session_state:
43
+ st.session_state.openAI_token = ""
44
+
45
+ if "case1" not in st.session_state:
46
+ st.session_state.case1 = ""
47
+
48
+ if "case2" not in st.session_state:
49
+ st.session_state.case2 = ""
50
+
51
+ if "case3" not in st.session_state:
52
+ st.session_state.case3 = ""
53
+
54
+ if "page2_tab" not in st.session_state:
55
+ st.session_state.page2_tab = "tab1"
56
+
57
+ if "total_debate_history" not in st.session_state:
58
+ st.session_state.total_debate_history = []
59
+
60
+ if "user_debate_history" not in st.session_state:
61
+ st.session_state.user_debate_history = []
62
+
63
+ if "bot_debate_history" not in st.session_state:
64
+ st.session_state.bot_debate_history = []
65
+
66
+ if "user_debate_time" not in st.session_state:
67
+ st.session_state.user_debate_time = ""
68
+
69
+ if "pros_and_cons" not in st.session_state:
70
+ st.session_state.pros_and_cons = ""
71
+
72
+ # Time session
73
+ if "start_time" not in st.session_state:
74
+ st.session_state.start_time = time.time()
75
+
76
+ if "end_time" not in st.session_state:
77
+ st.session_state.end_time = time.time()
78
+
79
+ if "debate_time" not in st.session_state:
80
+ st.session_state.debate_time = 0
81
+
82
+ if "pre_audio" not in st.session_state:
83
+ st.session_state.pre_audio = np.array([])
84
 
 
 
85
 
86
+ # Save function (placeholder)
87
+ def save_info(user_id, openAI_token, debate_theme):
88
+ # You can add the code to save the submitted info (e.g., to a database)
89
+ st.session_state.user_id = user_id
90
+ st.session_state.openAI_token = openAI_token
91
+ st.session_state.debate_theme = debate_theme
92
 
93
+ print("User ID:", user_id)
94
+ print("OpenAI token:", openAI_token)
95
+ print("Debate theme:", debate_theme)
96
 
97
+ # Session state
98
+ #session_state = SessionState.get(user_id="", openAI_token="", debate_theme="")
99
 
100
+ def write_info():
101
+ st.write('You choose', st.session_state.topic_list)
102
 
103
+ # for callback when button is clicked
104
+ def page_1_2_controller():
105
+ if st.session_state.user_id.strip() == "" or st.session_state.openAI_token.strip() == "":
106
+ st.session_state.page = "Page 1"
107
+ st.warning('Please fill in all the required fields.')
108
  else:
109
+ st.session_state.page = "Page 2"
110
+
111
+ def page_2_3_controller():
112
+ st.session_state.page = "Page 3"
113
+
114
+ def page2_tab_controller():
115
+ st.session_state.page2_tab = "tab2"
116
 
117
+ def page_3_4_controller():
118
+ st.session_state.page = "Page 4"
119
 
120
+ def page_4_5_controller():
121
+ st.session_state.page = "Page 5"
122
 
123
+ def page_5_6_controller():
124
+ st.session_state.page = "Page 6"
125
 
126
+ def page_2_6_controller():
127
+ st.session_state.page = "Page 6"
 
128
 
129
+ #########################################################
130
+ # Page 1
131
+ #########################################################
132
+ def page1():
133
 
134
+ # for local variables
135
+ topic_list = []
136
+
137
+ st.header('User Info & Debate Setting')
138
+ st.session_state.user_id = st.text_input(
139
+ label="Enter user ID",
140
+ max_chars=100,
141
+ placeholder="Enter user ID"
142
  )
143
+ # st.session_state.openAI_token = st.text_input(
144
+ # label="Enter OpenAI token",
145
+ # max_chars=200,
146
+ # placeholder="Enter OpenAI token"
147
+ # )
148
+
149
+ if st.button(
150
+ label='Submit all information',
151
+ on_click=page_1_2_controller
152
+ ):
153
+ # You can add a function here to save the submitted info
154
+ if st.session_state.user_id != '' and st.session_state.openAI_token != '':
155
+ save_info(
156
+ st.session_state.user_id,
157
+ st.session_state.openAI_token,
158
+ st.session_state.debate_theme
159
+ )
160
+ st.write('Information submitted successfully.')
161
+
162
+ #########################################################
163
+ # Page 2
164
+ #########################################################
165
+ def page2():
166
+ st.header("Choose Option")
167
+ option_result = st.selectbox("Choose your option", ["Total Debate", "Evaluation Only & Analyzing Utterances"])
168
+
169
+ # add controller
170
+ if option_result == "Total Debate":
171
+ page_control_func = page_2_3_controller
172
+ elif option_result == "Evaluation Only & Analyzing Utterances":
173
+ page_control_func = page_2_6_controller
174
+
175
+ if st.button(
176
+ label='Submit all information',
177
+ on_click=page_control_func
178
+ ):
179
+ st.write('Information submitted successfully.')
180
+
181
+
182
+ def page3():
183
+ #########################################################
184
+ # Tab 1 - Total Debate (토론 준비 -> 연습 -> 평가)
185
+ #########################################################
186
+ st.header("Total Debate")
187
+ debate_themes = ['Education','Sports','Religion','Justice','Pandemic','Politics','Minority','etc']
188
+
189
+ st.write("1. Select a debate theme")
190
+ st.session_state.debate_theme = st.selectbox("Choose your debate theme", debate_themes)
191
+
192
+ if st.session_state.debate_theme == 'Education':
193
+ topic_list = [
194
  "THBT college entrance examinations should accept students only on the basis of their academic performance in secondary education.",
195
  "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.",
196
  "THW abolish all requirements and evaluation criteria in higher education (i.e., attendance, exams, assignments)."
197
+ ]
198
+ #topic = st.selectbox("Select a topic_list", topic_list)
199
+ elif st.session_state.debate_theme == 'Sports':
200
+ topic_list = [
201
  "THBT having star players for team sports do more harm than good to the team.",
202
  "THR the emphasis on winning a medal in the Olympics as a core symbol of success.",
203
  "THP a world where sports serves purely entertainment purposes even at the expense of fair play."
204
+ ]
205
+ #topic = st.selectbox("Select a topic_list", topic_list)
206
+ elif st.session_state.debate_theme == 'Religion':
207
+ topic_list = [
208
  "THW, as a religious group/leader, cease attempts at increasing the number of believers and instead prioritize boosting loyalty amongst adherents to the religion.",
209
  "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.",
210
  "THW aggressively crackdown on megachurches."
211
+ ]
212
+ #topic = st.selectbox("Select a topic_list", topic_list)
213
+ elif st.session_state.debate_theme == 'Justice':
214
+ topic_list = [
215
  "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.",
216
  "In the case a human destroys the robot beyond repair, THW charge murder instead of property damage.",
217
  "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."
218
+ ]
219
+ #topic = st.selectbox("Select a topic_list", topic_list)
220
+ elif st.session_state.debate_theme == 'Pandemic':
221
+ topic_list = [
222
  "During a pandemic, THBT businesses that benefit from the pandemic should be additionally taxed.",
223
  "THW nullify the effect of medical patents in cases of medical emergencies.",
224
  "THW ban media content that denies the efficacy of the COVID-19 without substantial evidence."
225
+ ]
226
+ #topic = st.selectbox("Select a topic_list", topic_list)
227
+ elif st.session_state.debate_theme == 'Politics':
228
+ topic_list = [
229
  "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.",
230
  "THW impose a cap on the property and income of politicians.",
231
  "THW give the youth extra votes."
232
+ ]
233
+ #topic = st.selectbox("Select a topic_list", topic_list)
234
+ elif st.session_state.debate_theme == 'Minority':
235
+ topic_list = [
236
  "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.",
237
  "THBT the LGBTQIA+ movement should denounce the existence of marriage as opposed to fighting for equal marriage rights.",
238
  "THBT the LGBTQIA+ movement should condemn the consumption of movies and TV shows that cast straight actors/actresses in non-heterosexual identified roles."
239
+ ]
240
+ #topic = st.selectbox("Select a topic_list", topic_list)
241
  else:
242
+ topic_list = [
243
  "THW remove all laws that relate to filial responsibilities.",
244
  "THW require parents to receive approval from experts in relevant fields before making crucial decisions for their children.",
245
  "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.",
 
252
  "THW allow parents of severely mentally disabled children to medically impede their children's physical growth.",
253
  "THR the emphasis on longevity in relationships.",
254
  "Assuming feasibility, THW choose to continuously relive the happiest moment of one’s life."
255
+ ]
256
 
257
+ st.write("2. Select a topic")
258
+ st.session_state.topic = st.selectbox("Choose your topic", topic_list)
 
 
 
 
 
 
 
 
 
 
 
 
 
259
 
260
+ st.write("3. Write 3 cases")
 
 
 
261
 
262
+ case1 = st.text_area(
263
+ label="Case 1",
264
+ placeholder="Each case should be consisted of opinion, reasoning, and example.",
265
+ height=100
 
 
 
 
266
  )
267
+ case2 = st.text_area(
268
+ label="Case 2",
269
+ placeholder="Each case should be consisted of opinion, reasoning, and example.",
270
+ height=100
271
+ )
272
+ case3 = st.text_area(
273
+ label="Case 3",
274
+ placeholder="Each case should be consisted of opinion, reasoning, and example.",
275
+ height=100
276
+ )
277
+ case_error_message = st.empty()
278
+ st.session_state.pros_and_cons = st.selectbox("Choose your Side (Pros and Cons)", ["Pros", "Cons"])
279
+
280
+ start = st.button(label="Start Debate")
281
 
282
+ def validate_case(error_message):
283
+ if not case1 or not case2 or not case3:
284
+ case_error_message.error("Please fill out above all", icon="🚨")
285
+ return False
286
  else:
287
+ st.session_state.case1 = case1
288
+ st.session_state.case2 = case2
289
+ st.session_state.case3 = case3
290
+ return True
291
+
292
+ if start:
293
+ if validate_case(case_error_message):
294
+ page_3_4_controller()
295
+ st.experimental_rerun()
296
+
297
+ with st.sidebar:
298
+ st.sidebar.title('Ask to GPT')
299
+ user_input = st.sidebar.text_area(
300
+ label="Question",
301
+ placeholder="Input text here",
302
+ height=100)
303
+ output = st.sidebar.button("Ask")
304
+ input_error_message = st.empty()
305
+ if output:
306
+ if not user_input:
307
+ input_error_message.error("Please enter your question")
308
+ result = ""
309
+ else:
310
+ result = gpt_call(user_input)
311
+ else:
312
+ result = ""
313
+
314
+ st.sidebar.text_area(
315
+ label="Answer",
316
+ placeholder="(Answer will be shown here)",
317
+ value=result,
318
+ height=150)
319
+
320
+ #########################################################
321
+ # Page4
322
+ #########################################################
323
+
324
+ # generate response
325
+ def generate_response(prompt):
326
+ st.session_state['user_debate_history'].append(prompt)
327
+ st.session_state['total_debate_history'].append({"role": "user", "content": prompt})
328
+ response = gpt_call_context(st.session_state['total_debate_history'])
329
+ st.session_state['bot_debate_history'].append(response)
330
+ st.session_state['total_debate_history'].append({"role": "assistant", "content": response})
331
+ return response
332
+
333
+ def execute_stt(audio):
334
+ wav_file = open("audio/audio.wav", "wb")
335
+ wav_file.write(audio.tobytes())
336
+ wav_file.close()
337
+
338
+ audio_file= open("audio/audio.wav", "rb")
339
+ user_input = openai.Audio.transcribe("whisper-1", audio_file).text
340
+ audio_file.close()
341
+ return user_input
342
+
343
+ def page4():
344
+
345
+ # time
346
+ st.session_state.start_time = time.time()
347
+
348
+ with st.sidebar:
349
+ st.sidebar.title('Ask to GPT')
350
+ user_input = st.sidebar.text_area(
351
+ label="Question",
352
+ placeholder="Input text here",
353
+ height=100)
354
+ output = st.sidebar.button("Ask")
355
+ input_error_message = st.empty()
356
+ if output:
357
+ if not user_input:
358
+ input_error_message.error("Please enter your question")
359
+ result = ""
360
+ else:
361
+ result = gpt_call(user_input)
362
+ else:
363
+ result = ""
364
+
365
+ st.sidebar.text_area(
366
+ label="Answer",
367
+ placeholder="(Answer will be shown here)",
368
+ value=result,
369
+ height=150)
370
+
371
+ # default system prompt settings
372
+ if not st.session_state['total_debate_history']:
373
+ debate_preset = "\n".join([
374
+ "Debate Rules: ",
375
+ "1) This debate will be divided into two teams, pro and con, with two debates on each team.",
376
+ "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.",
377
+ "3) Answer logically with an introduction, body, and conclusion.", #add this one.
378
+ "4) Your role : " + st.session_state["pros_and_cons"] + " side debator",
379
+ "5) Debate subject: " + st.session_state['topic'],
380
+ ])
381
+ first_prompt = "Now we're going to start. Summarize the subject and your role. And ask user ready to begin."
382
+
383
+ st.session_state['total_debate_history'] = [
384
+ {"role": "system", "content": debate_preset}
385
+ ]
386
+ response = gpt_call(debate_preset + "\n" + first_prompt, role="system")
387
+ st.session_state['total_debate_history'].append({"role": "assistant", "content": response})
388
+ st.session_state['bot_debate_history'].append(response)
389
+
390
+ # container for chat history
391
+ response_container = st.container()
392
+ # container for text box
393
+ container = st.container()
394
+
395
+ with container:
396
+ with st.form(key='my_form', clear_on_submit=True):
397
+ user_input = None
398
+ # record voice
399
+ audio = audiorecorder("Click to record", "Recording...")
400
+ if np.array_equal(st.session_state['pre_audio'], audio):
401
+ audio = np.array([])
402
+ print("audio", audio)
403
+
404
+ #user_input = st.text_area("You:", key='input', height=100)
405
+ submit_buttom = st.form_submit_button(label='Send')
406
+ send_error_message = st.empty()
407
+
408
+ #if submit_buttom and user_input:
409
+ if submit_buttom:
410
+ if audio.any():
411
+ user_input = execute_stt(audio)
412
+ output = generate_response(user_input)
413
+ st.session_state['pre_audio'] = audio
414
+ else:
415
+ send_error_message.error("Please record your voice first", icon="🚨")
416
+ print("Nothing to transcribe")
417
+
418
+ #TODO 사용자 input이 없을 때도 reloading으로 buffering 걸리는 문제 해결
419
+ with response_container:
420
+ message(st.session_state['bot_debate_history'][0], key='0_bot')
421
+ text_to_speech = gTTS(text=st.session_state['bot_debate_history'][0], lang='en', slow=False)
422
+ text_to_speech.save(f'audio/test_gtts_0.mp3')
423
+ audio_file = open(f'audio/test_gtts_0.mp3', 'rb')
424
+ audio_bytes = audio_file.read()
425
+ st.audio(audio_bytes, format='audio/ogg')
426
+
427
+ for i in range(len(st.session_state['user_debate_history'])):
428
+ message(st.session_state['user_debate_history'][i], is_user=True, key=str(i)+'_user')
429
+ message(st.session_state['bot_debate_history'][i + 1], key=str(i + 1)+'_bot')
430
+ text_to_speech = gTTS(text=st.session_state['bot_debate_history'][i + 1], lang='en', slow=False)
431
+ text_to_speech.save(f'audio/test_gtts_{str(i + 1)}.mp3')
432
+ audio_file = open(f'audio/test_gtts_{str(i + 1)}.mp3', 'rb')
433
+ audio_bytes = audio_file.read()
434
+ st.audio(audio_bytes, format='audio/ogg')
435
+
436
+ if st.button(label="Next",
437
+ on_click=page_4_5_controller):
438
+ st.write('Information submitted successfully.')
439
+
440
+ print("#"*50)
441
+ print(st.session_state)
442
+ print("#"*50)
443
+
444
+ #########################################################
445
+ # Page5 - Total Debate Evaluation
446
+ #########################################################
447
+ def page5():
448
+
449
+ # end time
450
+ st.session_state.end_time = time.time()
451
+ st.session_state.debate_time = st.session_state.end_time - st.session_state.start_time
452
+
453
+ # st.tab
454
+ st.header('Total Debate Evaluation')
455
+
456
+ tab1, tab2 = st.tabs(['Debate Judgement', 'Debate Analysis'])
457
+
458
+ with tab1:
459
+ st.header("Debate Evaluation")
460
+
461
+ debate_themes = ['User-Bot', "User", "Bot"]
462
+
463
+ # 전체, 유저, 봇 세 가지 옵션 중에 선택
464
+ judgement_who = st.selectbox("Choose your debate theme", debate_themes)
465
+
466
+ with st.spinner('Wait for judgement result...'):
467
+ judgement_result = ""
468
+
469
+ user_debate_history = "".join(
470
+ st.session_state.user_debate_history
471
+ )
472
+ bot_debate_history = "".join(
473
+ st.session_state.bot_debate_history
474
+ )
475
+
476
+ judgement_result = debate_judgement(
477
+ judgement_who,
478
+ user_debate_history,
479
+ bot_debate_history
480
+ )
481
+
482
+ st.write("Debate Judgement Result")
483
+ st.write(judgement_result)
484
+ st.success('Done!')
485
+
486
+ with tab2:
487
+ st.header('Debate Analysis')
488
+
489
+ # 유저의 history를 기반으로 발화량, 빈출 단어, 발화 습관 세 가지를 분석
490
+ user_history = st.session_state.user_debate_history
491
+
492
+ # 1. 발화량: 총 단어, 평균 속도(단어/시간)를 평균 발화량 혹은 참고 지표와 비교해 제시
493
+
494
+ # 총 단어
495
+ # 텍스트를 단어로 분할합니다.
496
+ # 각 단어의 빈도를 계산합니다.
497
+ total_word_count = len(user_history)
498
+ #total_word_count = len(user_history.split())
499
+ st.write("Total Word Count: ", total_word_count)
500
+
501
+ # 평균 속도(단어/시간)
502
+ #user_debate_time = st.session_state.user_debate_time
503
+ average_word_per_time = total_word_count / st.session_state.debate_time # 시간 단위보고 나중에 수정하기
504
+ st.write("Average Word Per Time: ", average_word_per_time)
505
+
506
+ # 2. 빈출 단어: 반복해서 사용하는 단어 리스트
507
+ # 빈도 계산
508
+ frequency = Counter(user_history)
509
+ # 가장 빈도가 높은 데이터 출력
510
+ most_common_data = frequency.most_common(10)
511
+ print(most_common_data)
512
+ st.write("Most Common Words: ", most_common_data)
513
+
514
+ # 3. 발화 습관: 불필요한 언어습관(아, 음)
515
+ # whisper preprocesser에서 주면
516
+ disfluency_word_list = ['eh', 'umm', 'ah', 'uh', 'er', 'erm', 'err']
517
+ # Count the disfluency words
518
+ disfluency_counts = sum(user_word in disfluency_word_list for user_word in user_history)
519
+ st.write("Disfluency Counts: ", disfluency_counts)
520
+
521
+ # 유저와 봇의 대화 데이터가 세션에 남아있음
522
+ # st.session_state.debate_history
523
 
524
+
525
+ #########################################################
526
+ # Page6
527
+ #########################################################
528
+
529
+ def page6():
530
+
531
+ # end time
532
+ st.session_state.end_time = time.time()
533
+ st.session_state.debate_time = st.session_state.end_time - st.session_state.start_time
534
+
535
+ # st.tab
536
+ st.header('Total Debate Evaluation')
537
+
538
+ tab1, tab2 = st.tabs(['Debate Judgement', 'Debate Analysis'])
539
+
540
+ with tab1:
541
+ st.header("Debate Evaluation")
542
+
543
+ debate_themes = ['User-Bot', "User", "Bot"]
544
+
545
+ # 전체, 유저, 봇 세 가지 옵션 중에 선택
546
+ judgement_who = st.selectbox("Choose your debate theme", debate_themes)
547
+
548
+ judgement_result = ""
549
+ if judgement_result == "":
550
+ st.write("Wait for judgement result...")
551
+
552
+ user_debate_history = "".join(
553
+ st.session_state.user_debate_history
554
  )
555
+ bot_debate_history = "".join(
556
+ st.session_state.bot_debate_history
 
557
  )
558
 
559
+ judgement_result = debate_judgement(
560
+ judgement_who,
561
+ user_debate_history,
562
+ bot_debate_history
563
+ )
564
+
565
+ st.write("Debate Judgement Result")
566
+ st.write(judgement_result)
567
+
568
+ with tab2:
569
+ st.header('Debate Analysis')
570
+
571
+ # 유저의 history를 기반으로 발화량, 빈출 단어, 발화 습관 세 가지를 분석
572
+ user_history = st.session_state.user_debate_history
573
+
574
+ # 1. 발화량: 총 단어, 평균 속도(단어/시간)를 평균 발화량 혹은 참고 지표와 비교해 제시
575
+
576
+ # 총 단어
577
+ # 텍스트를 단어로 분할합니다.
578
+ # 각 단어의 빈도를 계산합니다.
579
+ total_word_count = len(user_history)
580
+ #total_word_count = len(user_history.split())
581
+ st.write("Total Word Count: ", total_word_count)
582
+
583
+ # 평균 속도(단어/시간)
584
+ #user_debate_time = st.session_state.user_debate_time
585
+ average_word_per_time = total_word_count / st.session_state.debate_time # 시간 단위보고 나중에 수정하기
586
+ st.write("Average Word Per Time: ", average_word_per_time)
587
+
588
+ # 2. 빈출 단어: 반복해서 사용하는 단어 리스트
589
+ # 빈도 계산
590
+ frequency = Counter(user_history)
591
+ # 가장 빈도가 높은 데이터 출력
592
+ most_common_data = frequency.most_common(10)
593
+ print(most_common_data)
594
+ st.write("Most Common Words: ", most_common_data)
595
+
596
+ # 3. 발화 습관: 불필요한 언어습관(아, 음)
597
+ # whisper preprocesser에서 주면
598
+ disfluency_word_list = ['eh', 'umm', 'ah', 'uh', 'er', 'erm', 'err']
599
+ # Count the disfluency words
600
+ disfluency_counts = sum(user_word in disfluency_word_list for user_word in user_history)
601
+ st.write("Disfluency Counts: ", disfluency_counts)
602
+
603
+ # 유저와 봇의 대화 데이터가 세션에 남아있음
604
+ # st.session_state.debate_history
605
+
606
+ ############################################
607
+ # Visualization
608
+ ############################################
609
+
610
+ # 이전에 기록된 값이 있다면, 그래프를 그립니다.
611
+ # 이전에 기록된 값이 없다면, 그래프를 그리지 않습니다.
612
+
613
+
614
+
615
+ #########################################################
616
+ # Page Routing
617
+ #########################################################
618
+ pages = {
619
+ "Page 1": page1, # user_id와 openai_key를 입력받는 페이지
620
+ "Page 2": page2, # 원하는 기능을 선택하는 페이지
621
+ "Page 3": page3, # Total Debate
622
+ "Page 4": page4, # Evaluation Only
623
+ "Page 5": page5, # Analyzing Utterances
624
+ "Page 6": page6,
625
+ }
626
+
627
+ selection = st.session_state.page
628
+ print("selection:", selection)
629
+
630
+ page = pages[selection]
631
+ # Execute selected page function
632
+ page()
633
 
 
 
634
 
 
 
 
 
 
 
 
 
 
 
 
 
vocal_app.py DELETED
@@ -1,631 +0,0 @@
1
- import streamlit as st
2
- import numpy as np
3
- import openai
4
-
5
- from gtts import gTTS
6
- from collections import Counter
7
- from streamlit_chat import message
8
-
9
- from dotenv import dotenv_values
10
- from bots.judgement_bot import debate_judgement
11
- from collections import Counter
12
- import time
13
-
14
- from audiorecorder import audiorecorder
15
-
16
- # modules
17
- from modules.gpt_modules import gpt_call, gpt_call_context
18
- #from modules.whisper_modules import transcribe
19
-
20
- config = dotenv_values(".env")
21
-
22
- openai.organization = config.get('OPENAI_ORGANIZATION')
23
- openai.api_key = config.get('OPENAI_API_KEY')
24
-
25
-
26
- # Page Configuration
27
- st.set_page_config(page_title="Streamlit App")
28
-
29
- # Initialize session state variables
30
- if "page" not in st.session_state:
31
- st.session_state.page = "Page 1"
32
-
33
- if "topic" not in st.session_state:
34
- st.session_state.topic = "None"
35
-
36
- if "user_id" not in st.session_state:
37
- st.session_state.user_id = ""
38
-
39
- if "openAI_token" not in st.session_state:
40
- st.session_state.openAI_token = ""
41
-
42
- if "case1" not in st.session_state:
43
- st.session_state.case1 = ""
44
-
45
- if "case2" not in st.session_state:
46
- st.session_state.case2 = ""
47
-
48
- if "case3" not in st.session_state:
49
- st.session_state.case3 = ""
50
-
51
- if "page2_tab" not in st.session_state:
52
- st.session_state.page2_tab = "tab1"
53
-
54
- if "total_debate_history" not in st.session_state:
55
- st.session_state.total_debate_history = []
56
-
57
- if "user_debate_history" not in st.session_state:
58
- st.session_state.user_debate_history = []
59
-
60
- if "bot_debate_history" not in st.session_state:
61
- st.session_state.bot_debate_history = []
62
-
63
- if "user_debate_time" not in st.session_state:
64
- st.session_state.user_debate_time = ""
65
-
66
- if "pros_and_cons" not in st.session_state:
67
- st.session_state.pros_and_cons = ""
68
-
69
- # Time session
70
- if "start_time" not in st.session_state:
71
- st.session_state.start_time = time.time()
72
-
73
- if "end_time" not in st.session_state:
74
- st.session_state.end_time = time.time()
75
-
76
- if "debate_time" not in st.session_state:
77
- st.session_state.debate_time = 0
78
-
79
- if "pre_audio" not in st.session_state:
80
- st.session_state.pre_audio = np.array([])
81
-
82
-
83
- # Save function (placeholder)
84
- def save_info(user_id, openAI_token, debate_theme):
85
- # You can add the code to save the submitted info (e.g., to a database)
86
- st.session_state.user_id = user_id
87
- st.session_state.openAI_token = openAI_token
88
- st.session_state.debate_theme = debate_theme
89
-
90
- print("User ID:", user_id)
91
- print("OpenAI token:", openAI_token)
92
- print("Debate theme:", debate_theme)
93
-
94
- # Session state
95
- #session_state = SessionState.get(user_id="", openAI_token="", debate_theme="")
96
-
97
- def write_info():
98
- st.write('You choose', st.session_state.topic_list)
99
-
100
- # for callback when button is clicked
101
- def page_1_2_controller():
102
- if st.session_state.user_id.strip() == "" or st.session_state.openAI_token.strip() == "":
103
- st.session_state.page = "Page 1"
104
- st.warning('Please fill in all the required fields.')
105
- else:
106
- st.session_state.page = "Page 2"
107
-
108
- def page_2_3_controller():
109
- st.session_state.page = "Page 3"
110
-
111
- def page2_tab_controller():
112
- st.session_state.page2_tab = "tab2"
113
-
114
- def page_3_4_controller():
115
- st.session_state.page = "Page 4"
116
-
117
- def page_4_5_controller():
118
- st.session_state.page = "Page 5"
119
-
120
- def page_5_6_controller():
121
- st.session_state.page = "Page 6"
122
-
123
- def page_2_6_controller():
124
- st.session_state.page = "Page 6"
125
-
126
- #########################################################
127
- # Page 1
128
- #########################################################
129
- def page1():
130
-
131
- # for local variables
132
- topic_list = []
133
-
134
- st.header('User Info & Debate Setting')
135
- st.session_state.user_id = st.text_input(
136
- label="Enter user ID",
137
- max_chars=100,
138
- placeholder="Enter user ID"
139
- )
140
- st.session_state.openAI_token = st.text_input(
141
- label="Enter OpenAI token",
142
- max_chars=200,
143
- placeholder="Enter OpenAI token"
144
- )
145
-
146
- if st.button(
147
- label='Submit all information',
148
- on_click=page_1_2_controller
149
- ):
150
- # You can add a function here to save the submitted info
151
- if st.session_state.user_id != '' and st.session_state.openAI_token != '':
152
- save_info(
153
- st.session_state.user_id,
154
- st.session_state.openAI_token,
155
- st.session_state.debate_theme
156
- )
157
- st.write('Information submitted successfully.')
158
-
159
- #########################################################
160
- # Page 2
161
- #########################################################
162
- def page2():
163
- st.header("Choose Option")
164
- option_result = st.selectbox("Choose your option", ["Total Debate", "Evaluation Only & Analyzing Utterances"])
165
-
166
- # add controller
167
- if option_result == "Total Debate":
168
- page_control_func = page_2_3_controller
169
- elif option_result == "Evaluation Only & Analyzing Utterances":
170
- page_control_func = page_2_6_controller
171
-
172
- if st.button(
173
- label='Submit all information',
174
- on_click=page_control_func
175
- ):
176
- st.write('Information submitted successfully.')
177
-
178
-
179
- def page3():
180
- #########################################################
181
- # Tab 1 - Total Debate (토론 준비 -> 연습 -> 평가)
182
- #########################################################
183
- st.header("Total Debate")
184
- debate_themes = ['Education','Sports','Religion','Justice','Pandemic','Politics','Minority','etc']
185
-
186
- st.write("1. Select a debate theme")
187
- st.session_state.debate_theme = st.selectbox("Choose your debate theme", debate_themes)
188
-
189
- if st.session_state.debate_theme == 'Education':
190
- topic_list = [
191
- "THBT college entrance examinations should accept students only on the basis of their academic performance in secondary education.",
192
- "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.",
193
- "THW abolish all requirements and evaluation criteria in higher education (i.e., attendance, exams, assignments)."
194
- ]
195
- #topic = st.selectbox("Select a topic_list", topic_list)
196
- elif st.session_state.debate_theme == 'Sports':
197
- topic_list = [
198
- "THBT having star players for team sports do more harm than good to the team.",
199
- "THR the emphasis on winning a medal in the Olympics as a core symbol of success.",
200
- "THP a world where sports serves purely entertainment purposes even at the expense of fair play."
201
- ]
202
- #topic = st.selectbox("Select a topic_list", topic_list)
203
- elif st.session_state.debate_theme == 'Religion':
204
- topic_list = [
205
- "THW, as a religious group/leader, cease attempts at increasing the number of believers and instead prioritize boosting loyalty amongst adherents to the religion.",
206
- "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.",
207
- "THW aggressively crackdown on megachurches."
208
- ]
209
- #topic = st.selectbox("Select a topic_list", topic_list)
210
- elif st.session_state.debate_theme == 'Justice':
211
- topic_list = [
212
- "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.",
213
- "In the case a human destroys the robot beyond repair, THW charge murder instead of property damage.",
214
- "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."
215
- ]
216
- #topic = st.selectbox("Select a topic_list", topic_list)
217
- elif st.session_state.debate_theme == 'Pandemic':
218
- topic_list = [
219
- "During a pandemic, THBT businesses that benefit from the pandemic should be additionally taxed.",
220
- "THW nullify the effect of medical patents in cases of medical emergencies.",
221
- "THW ban media content that denies the efficacy of the COVID-19 without substantial evidence."
222
- ]
223
- #topic = st.selectbox("Select a topic_list", topic_list)
224
- elif st.session_state.debate_theme == 'Politics':
225
- topic_list = [
226
- "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.",
227
- "THW impose a cap on the property and income of politicians.",
228
- "THW give the youth extra votes."
229
- ]
230
- #topic = st.selectbox("Select a topic_list", topic_list)
231
- elif st.session_state.debate_theme == 'Minority':
232
- topic_list = [
233
- "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.",
234
- "THBT the LGBTQIA+ movement should denounce the existence of marriage as opposed to fighting for equal marriage rights.",
235
- "THBT the LGBTQIA+ movement should condemn the consumption of movies and TV shows that cast straight actors/actresses in non-heterosexual identified roles."
236
- ]
237
- #topic = st.selectbox("Select a topic_list", topic_list)
238
- else:
239
- topic_list = [
240
- "THW remove all laws that relate to filial responsibilities.",
241
- "THW require parents to receive approval from experts in relevant fields before making crucial decisions for their children.",
242
- "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.",
243
- "THBT any upper limits on prison sentences for particularly heinous crimes should be abolished.",
244
- "THW require dating apps to anonymize profile pictures.",
245
- "THW adopt a Pass/Fail grading system for students who suffer from mental health problems (e.g. depression, bipolar disorder, etc.).",
246
- "THBT South Korean feminist movements should reject feminist icons that are adversarial and embody violence.",
247
- "THBT freedom of speech should be considered obsolete.",
248
- "THR the narrative that eccentric personalities are essential to create art.",
249
- "THW allow parents of severely mentally disabled children to medically impede their children's physical growth.",
250
- "THR the emphasis on longevity in relationships.",
251
- "Assuming feasibility, THW choose to continuously relive the happiest moment of one’s life."
252
- ]
253
-
254
- st.write("2. Select a topic")
255
- st.session_state.topic = st.selectbox("Choose your topic", topic_list)
256
-
257
- st.write("3. Write 3 cases")
258
-
259
- case1 = st.text_area(
260
- label="Case 1",
261
- placeholder="Each case should be consisted of opinion, reasoning, and example.",
262
- height=100
263
- )
264
- case2 = st.text_area(
265
- label="Case 2",
266
- placeholder="Each case should be consisted of opinion, reasoning, and example.",
267
- height=100
268
- )
269
- case3 = st.text_area(
270
- label="Case 3",
271
- placeholder="Each case should be consisted of opinion, reasoning, and example.",
272
- height=100
273
- )
274
- case_error_message = st.empty()
275
- st.session_state.pros_and_cons = st.selectbox("Choose your Side (Pros and Cons)", ["Pros", "Cons"])
276
-
277
- start = st.button(label="Start Debate")
278
-
279
- def validate_case(error_message):
280
- if not case1 or not case2 or not case3:
281
- case_error_message.error("Please fill out above all", icon="🚨")
282
- return False
283
- else:
284
- st.session_state.case1 = case1
285
- st.session_state.case2 = case2
286
- st.session_state.case3 = case3
287
- return True
288
-
289
- if start:
290
- if validate_case(case_error_message):
291
- page_3_4_controller()
292
- st.experimental_rerun()
293
-
294
- with st.sidebar:
295
- st.sidebar.title('Ask to GPT')
296
- user_input = st.sidebar.text_area(
297
- label="Question",
298
- placeholder="Input text here",
299
- height=100)
300
- output = st.sidebar.button("Ask")
301
- input_error_message = st.empty()
302
- if output:
303
- if not user_input:
304
- input_error_message.error("Please enter your question")
305
- result = ""
306
- else:
307
- result = gpt_call(user_input)
308
- else:
309
- result = ""
310
-
311
- st.sidebar.text_area(
312
- label="Answer",
313
- placeholder="(Answer will be shown here)",
314
- value=result,
315
- height=150)
316
-
317
- #########################################################
318
- # Page4
319
- #########################################################
320
-
321
- # generate response
322
- def generate_response(prompt):
323
- st.session_state['user_debate_history'].append(prompt)
324
- st.session_state['total_debate_history'].append({"role": "user", "content": prompt})
325
- response = gpt_call_context(st.session_state['total_debate_history'])
326
- st.session_state['bot_debate_history'].append(response)
327
- st.session_state['total_debate_history'].append({"role": "assistant", "content": response})
328
- return response
329
-
330
- def execute_stt(audio):
331
- wav_file = open("audio/audio.wav", "wb")
332
- wav_file.write(audio.tobytes())
333
- wav_file.close()
334
-
335
- audio_file= open("audio/audio.wav", "rb")
336
- user_input = openai.Audio.transcribe("whisper-1", audio_file).text
337
- audio_file.close()
338
- return user_input
339
-
340
- def page4():
341
-
342
- # time
343
- st.session_state.start_time = time.time()
344
-
345
- with st.sidebar:
346
- st.sidebar.title('Ask to GPT')
347
- user_input = st.sidebar.text_area(
348
- label="Question",
349
- placeholder="Input text here",
350
- height=100)
351
- output = st.sidebar.button("Ask")
352
- input_error_message = st.empty()
353
- if output:
354
- if not user_input:
355
- input_error_message.error("Please enter your question")
356
- result = ""
357
- else:
358
- result = gpt_call(user_input)
359
- else:
360
- result = ""
361
-
362
- st.sidebar.text_area(
363
- label="Answer",
364
- placeholder="(Answer will be shown here)",
365
- value=result,
366
- height=150)
367
-
368
- # default system prompt settings
369
- if not st.session_state['total_debate_history']:
370
- debate_preset = "\n".join([
371
- "Debate Rules: ",
372
- "1) This debate will be divided into two teams, pro and con, with two debates on each team.",
373
- "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.",
374
- "3) Answer logically with an introduction, body, and conclusion.", #add this one.
375
- "4) Your role : " + st.session_state["pros_and_cons"] + " side debator",
376
- "5) Debate subject: " + st.session_state['topic'],
377
- ])
378
- first_prompt = "Now we're going to start. Summarize the subject and your role. And ask user ready to begin."
379
-
380
- st.session_state['total_debate_history'] = [
381
- {"role": "system", "content": debate_preset}
382
- ]
383
- response = gpt_call(debate_preset + "\n" + first_prompt, role="system")
384
- st.session_state['total_debate_history'].append({"role": "assistant", "content": response})
385
- st.session_state['bot_debate_history'].append(response)
386
-
387
- # container for chat history
388
- response_container = st.container()
389
- # container for text box
390
- container = st.container()
391
-
392
- with container:
393
- with st.form(key='my_form', clear_on_submit=True):
394
- user_input = None
395
- # record voice
396
- audio = audiorecorder("Click to record", "Recording...")
397
- if np.array_equal(st.session_state['pre_audio'], audio):
398
- audio = np.array([])
399
- print("audio", audio)
400
-
401
- #user_input = st.text_area("You:", key='input', height=100)
402
- submit_buttom = st.form_submit_button(label='Send')
403
- send_error_message = st.empty()
404
-
405
- #if submit_buttom and user_input:
406
- if submit_buttom:
407
- if audio.any():
408
- user_input = execute_stt(audio)
409
- output = generate_response(user_input)
410
- st.session_state['pre_audio'] = audio
411
- else:
412
- send_error_message.error("Please record your voice first", icon="🚨")
413
- print("Nothing to transcribe")
414
-
415
- #TODO 사용자 input이 없을 때도 reloading으로 buffering 걸리는 문제 해결
416
- with response_container:
417
- message(st.session_state['bot_debate_history'][0], key='0_bot')
418
- text_to_speech = gTTS(text=st.session_state['bot_debate_history'][0], lang='en', slow=False)
419
- text_to_speech.save(f'audio/test_gtts_0.mp3')
420
- audio_file = open(f'audio/test_gtts_0.mp3', 'rb')
421
- audio_bytes = audio_file.read()
422
- st.audio(audio_bytes, format='audio/ogg')
423
-
424
- for i in range(len(st.session_state['user_debate_history'])):
425
- message(st.session_state['user_debate_history'][i], is_user=True, key=str(i)+'_user')
426
- message(st.session_state['bot_debate_history'][i + 1], key=str(i + 1)+'_bot')
427
- text_to_speech = gTTS(text=st.session_state['bot_debate_history'][i + 1], lang='en', slow=False)
428
- text_to_speech.save(f'audio/test_gtts_{str(i + 1)}.mp3')
429
- audio_file = open(f'audio/test_gtts_{str(i + 1)}.mp3', 'rb')
430
- audio_bytes = audio_file.read()
431
- st.audio(audio_bytes, format='audio/ogg')
432
-
433
- if st.button(label="Next",
434
- on_click=page_4_5_controller):
435
- st.write('Information submitted successfully.')
436
-
437
- print("#"*50)
438
- print(st.session_state)
439
- print("#"*50)
440
-
441
- #########################################################
442
- # Page5 - Total Debate Evaluation
443
- #########################################################
444
- def page5():
445
-
446
- # end time
447
- st.session_state.end_time = time.time()
448
- st.session_state.debate_time = st.session_state.end_time - st.session_state.start_time
449
-
450
- # st.tab
451
- st.header('Total Debate Evaluation')
452
-
453
- tab1, tab2 = st.tabs(['Debate Judgement', 'Debate Analysis'])
454
-
455
- with tab1:
456
- st.header("Debate Evaluation")
457
-
458
- debate_themes = ['User-Bot', "User", "Bot"]
459
-
460
- # 전체, 유저, 봇 세 가지 옵션 중에 선택
461
- judgement_who = st.selectbox("Choose your debate theme", debate_themes)
462
-
463
- with st.spinner('Wait for judgement result...'):
464
- judgement_result = ""
465
-
466
- user_debate_history = "".join(
467
- st.session_state.user_debate_history
468
- )
469
- bot_debate_history = "".join(
470
- st.session_state.bot_debate_history
471
- )
472
-
473
- judgement_result = debate_judgement(
474
- judgement_who,
475
- user_debate_history,
476
- bot_debate_history
477
- )
478
-
479
- st.write("Debate Judgement Result")
480
- st.write(judgement_result)
481
- st.success('Done!')
482
-
483
- with tab2:
484
- st.header('Debate Analysis')
485
-
486
- # 유저의 history를 기반으로 발화량, 빈출 단어, 발화 습관 세 가지를 분석
487
- user_history = st.session_state.user_debate_history
488
-
489
- # 1. 발화량: 총 단어, 평균 속도(단어/시간)를 평균 발화량 혹은 참고 지표와 비교해 제시
490
-
491
- # 총 단어
492
- # 텍스트를 단어로 분할합니다.
493
- # 각 단어의 빈도를 계산합니다.
494
- total_word_count = len(user_history)
495
- #total_word_count = len(user_history.split())
496
- st.write("Total Word Count: ", total_word_count)
497
-
498
- # 평균 속도(단어/시간)
499
- #user_debate_time = st.session_state.user_debate_time
500
- average_word_per_time = total_word_count / st.session_state.debate_time # 시간 단위보고 나중에 수정하기
501
- st.write("Average Word Per Time: ", average_word_per_time)
502
-
503
- # 2. 빈출 단어: 반복해서 사용하는 단어 리스트
504
- # 빈도 계산
505
- frequency = Counter(user_history)
506
- # 가장 빈도가 높은 데이터 출력
507
- most_common_data = frequency.most_common(10)
508
- print(most_common_data)
509
- st.write("Most Common Words: ", most_common_data)
510
-
511
- # 3. 발화 습관: 불필요한 언어습관(아, 음)
512
- # whisper preprocesser에서 주면
513
- disfluency_word_list = ['eh', 'umm', 'ah', 'uh', 'er', 'erm', 'err']
514
- # Count the disfluency words
515
- disfluency_counts = sum(user_word in disfluency_word_list for user_word in user_history)
516
- st.write("Disfluency Counts: ", disfluency_counts)
517
-
518
- # 유저와 봇의 대화 데이터가 세션에 남아있음
519
- # st.session_state.debate_history
520
-
521
-
522
- #########################################################
523
- # Page6
524
- #########################################################
525
-
526
- def page6():
527
-
528
- # end time
529
- st.session_state.end_time = time.time()
530
- st.session_state.debate_time = st.session_state.end_time - st.session_state.start_time
531
-
532
- # st.tab
533
- st.header('Total Debate Evaluation')
534
-
535
- tab1, tab2 = st.tabs(['Debate Judgement', 'Debate Analysis'])
536
-
537
- with tab1:
538
- st.header("Debate Evaluation")
539
-
540
- debate_themes = ['User-Bot', "User", "Bot"]
541
-
542
- # 전체, 유저, 봇 세 가지 옵션 중에 선택
543
- judgement_who = st.selectbox("Choose your debate theme", debate_themes)
544
-
545
- judgement_result = ""
546
- if judgement_result == "":
547
- st.write("Wait for judgement result...")
548
-
549
- user_debate_history = "".join(
550
- st.session_state.user_debate_history
551
- )
552
- bot_debate_history = "".join(
553
- st.session_state.bot_debate_history
554
- )
555
-
556
- judgement_result = debate_judgement(
557
- judgement_who,
558
- user_debate_history,
559
- bot_debate_history
560
- )
561
-
562
- st.write("Debate Judgement Result")
563
- st.write(judgement_result)
564
-
565
- with tab2:
566
- st.header('Debate Analysis')
567
-
568
- # 유저의 history를 기반으로 발화량, 빈출 단어, 발화 습관 세 가지를 분석
569
- user_history = st.session_state.user_debate_history
570
-
571
- # 1. 발화량: 총 단어, 평균 속도(단어/시간)를 평균 발화량 혹은 참고 지표와 비교해 제시
572
-
573
- # 총 단어
574
- # 텍스트를 단어로 분할합니다.
575
- # 각 단어의 빈도를 계산합니다.
576
- total_word_count = len(user_history)
577
- #total_word_count = len(user_history.split())
578
- st.write("Total Word Count: ", total_word_count)
579
-
580
- # 평균 속도(단어/시간)
581
- #user_debate_time = st.session_state.user_debate_time
582
- average_word_per_time = total_word_count / st.session_state.debate_time # 시간 단위보고 나중에 수정하기
583
- st.write("Average Word Per Time: ", average_word_per_time)
584
-
585
- # 2. 빈출 단어: 반복해서 사용하는 단어 리스트
586
- # 빈도 계산
587
- frequency = Counter(user_history)
588
- # 가장 빈도가 높은 데이터 출력
589
- most_common_data = frequency.most_common(10)
590
- print(most_common_data)
591
- st.write("Most Common Words: ", most_common_data)
592
-
593
- # 3. 발화 습관: 불필요한 언어습관(아, 음)
594
- # whisper preprocesser에서 주면
595
- disfluency_word_list = ['eh', 'umm', 'ah', 'uh', 'er', 'erm', 'err']
596
- # Count the disfluency words
597
- disfluency_counts = sum(user_word in disfluency_word_list for user_word in user_history)
598
- st.write("Disfluency Counts: ", disfluency_counts)
599
-
600
- # 유저와 봇의 대화 데이터가 세션에 남아있음
601
- # st.session_state.debate_history
602
-
603
- ############################################
604
- # Visualization
605
- ############################################
606
-
607
- # 이전에 기록된 값이 있다면, 그래프를 그립니다.
608
- # 이전에 기록된 값이 없다면, 그래프를 그리지 않습니다.
609
-
610
-
611
-
612
- #########################################################
613
- # Page Routing
614
- #########################################################
615
- pages = {
616
- "Page 1": page1, # user_id와 openai_key를 입력받는 페이지
617
- "Page 2": page2, # 원하는 ��능을 선택하는 페이지
618
- "Page 3": page3, # Total Debate
619
- "Page 4": page4, # Evaluation Only
620
- "Page 5": page5, # Analyzing Utterances
621
- "Page 6": page6,
622
- }
623
-
624
- selection = st.session_state.page
625
- print("selection:", selection)
626
-
627
- page = pages[selection]
628
- # Execute selected page function
629
- page()
630
-
631
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vocal_app.sh DELETED
@@ -1 +0,0 @@
1
- streamlit run vocal_app.py