Ridealist commited on
Commit
ac10408
2 Parent(s): f8d4e3f 08fc888

Merge remote-tracking branch 'upstream/master' into prototype_v0.1

Browse files
.github/workflows/cd.yml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face hub
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - master
7
+ paths-ignore: ["/README.md"]
8
+
9
+ workflow_dispatch:
10
+
11
+ jobs:
12
+ sync-to-hub:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v3
16
+ with:
17
+ fetch-depth: 0
18
+ lfs: true
19
+ - name: Push to hub
20
+ env:
21
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
22
+ run: git push https://Ridealist:$HF_TOKEN@huggingface.co/spaces/Ridealist/chat_bot main
23
+
app.py CHANGED
@@ -8,6 +8,7 @@ from collections import Counter
8
  from streamlit_chat import message
9
 
10
  from bots.judgement_bot import debate_judgement
 
11
  import time
12
  from time import strftime
13
 
@@ -93,6 +94,9 @@ if "pre_audio" not in st.session_state:
93
  if "session_num" not in st.session_state:
94
  st.session_state.session_num = 0
95
 
 
 
 
96
 
97
  #########################################################
98
  # Save function (placeholder)
@@ -161,9 +165,11 @@ def page_n_1_controller():
161
  # Page 1
162
  #########################################################
163
  def page1():
164
- _, _, _, home = st.columns([5, 5, 1, 1])
165
- with home:
166
- st.button("🔝", on_click=page_n_1_controller, use_container_width=True)
 
 
167
 
168
  st.header('User Info')
169
  st.session_state.user_id = st.text_input(
@@ -451,24 +457,39 @@ def page4():
451
  #########################################################
452
 
453
  def generate_response(prompt):
 
454
  st.session_state['user_debate_history'].append(prompt)
455
  st.session_state['total_debate_history'].append({"role": "user", "content": prompt})
456
- response = gpt_call_context(st.session_state['total_debate_history'])
 
 
 
 
 
457
  st.session_state['bot_debate_history'].append(response)
458
  st.session_state['total_debate_history'].append({"role": "assistant", "content": response})
459
  return response
460
 
461
  def execute_stt(audio, error_message):
462
- wav_file = open("audio/audio.wav", "wb")
 
 
 
 
 
 
463
  wav_file.write(audio.tobytes())
464
- wav_file.close()
465
  try:
466
- user_input = whisper_transcribe(audio)
467
  except:
468
  error_message.error("Whisper Error : The engine is currently overloaded, it will be auto-reloaded in a second")
469
  time.sleep(1)
470
  st.experimental_rerun()
471
 
 
 
 
472
  return user_input
473
 
474
  def page5():
@@ -583,8 +604,10 @@ def page5():
583
  if submit_buttom:
584
  if audio.any():
585
  user_input = execute_stt(audio, openai_error_bottom)
 
586
  try :
587
  response = generate_response(user_input)
 
588
  except:
589
  openai_error_bottom.error("Chat-GPT Error : The engine is currently overloaded, it will be auto-reloaded in a second")
590
  time.sleep(1)
@@ -670,48 +693,59 @@ def page6():
670
 
671
  st.write('Note that evaluation using GPT is an experimental feature. Please check it out and give us your feedback.')
672
 
673
- tab1, tab2 = st.tabs(['Debate Evaluation', 'Debate Analysis'])
674
 
675
  with tab1:
676
  st.header("Debate Evaluation")
677
-
678
- debate_themes = ['User-Bot', "User", "Bot"]
679
 
680
  # 전체, 유저, 봇 세 가지 옵션 중에 선택
681
- judgement_who = st.selectbox("Choose your debate theme", debate_themes)
682
 
683
- with st.spinner('Wait for judgement result...'):
684
- judgement_result = ""
 
685
 
686
- user_debate_history = "".join(
687
- st.session_state.user_debate_history
688
- )
689
- bot_debate_history = "".join(
690
- st.session_state.bot_debate_history
691
- )
692
-
693
- judgement_result = debate_judgement(
694
- judgement_who,
695
- user_debate_history,
696
- bot_debate_history
697
  )
698
 
699
- st.write("Debate Judgement Result")
700
- st.write(judgement_result)
 
 
701
 
702
- if judgement_result != "":
703
- put_item(
704
- table=dynamodb.Table('DEBO_evaluation'),
705
- item={
706
- 'user_id': st.session_state.user_id,
707
- 'time_stamp': time_stamp,
708
- 'judgement_text': judgement_result,
709
- 'session_num': st.session_state.session_num,
710
- }
711
- )
712
- st.success('Done!')
 
 
 
 
 
713
 
714
  with tab2:
 
 
 
 
 
 
 
 
 
 
 
715
  st.header('Debate Analysis')
716
 
717
  # 유저의 history를 기반으로 발화량, 빈출 단어, 발화 습관 세 가지를 분석
@@ -722,7 +756,10 @@ def page6():
722
  # 총 단어
723
  # 텍스트를 단어로 분할합니다.
724
  # 각 단어의 빈도를 계산합니다.
725
- total_word_count = len(user_history)
 
 
 
726
  #total_word_count = len(user_history.split())
727
  st.write("Total Word Count: ", total_word_count)
728
 
@@ -733,11 +770,16 @@ def page6():
733
 
734
  # 2. 빈출 단어: 반복해서 사용하는 단어 리스트
735
  # 빈도 계산
736
- frequency = Counter(user_history)
737
  # 가장 빈도가 높은 데이터 출력
738
- most_common_data = frequency.most_common(10)
739
- print(most_common_data)
740
- st.write("Most Common Words: ", most_common_data)
 
 
 
 
 
741
 
742
  # 3. 발화 습관: 불필요한 언어습관(아, 음)
743
  # whisper preprocesser에서 주면
@@ -747,13 +789,6 @@ def page6():
747
  st.write("Disfluency Counts: ", disfluency_counts)
748
 
749
  if total_word_count != "" and average_word_per_time != "" and disfluency_counts != "":
750
-
751
- print("user_id", type(st.session_state.user_id))
752
- print("time_stamp", type(time_stamp))
753
- print("total_word_count", type(total_word_count))
754
- print("average_word_per_time", type(average_word_per_time))
755
- print("disfluency_counts", type(disfluency_counts))
756
- print("session_num", type(st.session_state.session_num))
757
 
758
  put_item(
759
  table=dynamodb.Table('DEBO_debate_analysis'),
@@ -799,36 +834,41 @@ def page7():
799
  # 전체, 유저, 봇 세 가지 옵션 중에 선택
800
  judgement_who = st.selectbox("Choose your debate theme", debate_themes)
801
 
802
- with st.spinner('Wait for judgement result...'):
803
- judgement_result = ""
804
-
805
- user_debate_history = "".join(
806
- st.session_state.user_debate_history
807
- )
808
- bot_debate_history = "".join(
809
- st.session_state.bot_debate_history
810
- )
811
 
812
- judgement_result = debate_judgement(
813
- judgement_who,
814
- user_debate_history,
815
- bot_debate_history
 
816
  )
817
-
818
- st.write("Debate Judgement Result")
819
- st.write(judgement_result)
820
 
821
- if judgement_result:
822
- put_item(
823
- table=dynamodb.Table('DEBO_evaluation'),
824
- item={
825
- 'user_id': st.session_state.user_id,
826
- 'time_stamp': time_stamp,
827
- 'judgement_text': judgement_result,
828
- 'session_num': int(st.session_state.session_num),
829
- }
830
  )
831
- st.success('Done!')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
832
 
833
  with tab2:
834
  st.header('Debate Analysis')
 
8
  from streamlit_chat import message
9
 
10
  from bots.judgement_bot import debate_judgement
11
+ from bots.perfect_case_bot import perfect_case_selector
12
  import time
13
  from time import strftime
14
 
 
94
  if "session_num" not in st.session_state:
95
  st.session_state.session_num = 0
96
 
97
+ if "judgement_result" not in st.session_state:
98
+ st.session_state.judgement_result = ""
99
+
100
 
101
  #########################################################
102
  # Save function (placeholder)
 
165
  # Page 1
166
  #########################################################
167
  def page1():
168
+
169
+ # 첫페이지는 home이 따로 필요없을 것 같아서 주석처리함
170
+ #_, _, _, home = st.columns([5, 5, 1, 1])
171
+ # with home:
172
+ # st.button("🔝", on_click=page_n_1_controller, use_container_width=True)
173
 
174
  st.header('User Info')
175
  st.session_state.user_id = st.text_input(
 
457
  #########################################################
458
 
459
  def generate_response(prompt):
460
+
461
  st.session_state['user_debate_history'].append(prompt)
462
  st.session_state['total_debate_history'].append({"role": "user", "content": prompt})
463
+
464
+ if len(prompt.split()) < 10:
465
+ response = "Please speak longer!"
466
+ else:
467
+ response = gpt_call_context(st.session_state['total_debate_history'])
468
+
469
  st.session_state['bot_debate_history'].append(response)
470
  st.session_state['total_debate_history'].append({"role": "assistant", "content": response})
471
  return response
472
 
473
  def execute_stt(audio, error_message):
474
+
475
+ # audio 기록 누적
476
+ #user_audio_path = "audio/" + str(st.session_state.user_id) + "_" + str(st.session_state.session_num) + "_" + str(time.time()) + ".wav"
477
+ # audio 기록을 누적하고 싶지 않다면
478
+ user_audio_path = "audio/audio.wav"
479
+
480
+ wav_file = open(user_audio_path, "wb")
481
  wav_file.write(audio.tobytes())
482
+
483
  try:
484
+ user_input = whisper_transcribe(wav_file)
485
  except:
486
  error_message.error("Whisper Error : The engine is currently overloaded, it will be auto-reloaded in a second")
487
  time.sleep(1)
488
  st.experimental_rerun()
489
 
490
+ # close file
491
+ wav_file.close()
492
+
493
  return user_input
494
 
495
  def page5():
 
604
  if submit_buttom:
605
  if audio.any():
606
  user_input = execute_stt(audio, openai_error_bottom)
607
+
608
  try :
609
  response = generate_response(user_input)
610
+ print("response", response)
611
  except:
612
  openai_error_bottom.error("Chat-GPT Error : The engine is currently overloaded, it will be auto-reloaded in a second")
613
  time.sleep(1)
 
693
 
694
  st.write('Note that evaluation using GPT is an experimental feature. Please check it out and give us your feedback.')
695
 
696
+ tab1, tab2, tab3 = st.tabs(['Debate Evaluation', 'Perfect Case', 'Debate Analysis'])
697
 
698
  with tab1:
699
  st.header("Debate Evaluation")
 
 
700
 
701
  # 전체, 유저, 봇 세 가지 옵션 중에 선택
702
+ #judgement_who = st.selectbox("Choose what you want! (Evaluation result / Perfect case on this theme)", debate_themes)
703
 
704
+ if st.session_state.judgement_result == "":
705
+ with st.spinner('Wait for judgement result...'):
706
+ judgement_result = ""
707
 
708
+ user_debate_history = "".join(
709
+ st.session_state.user_debate_history
710
+ )
711
+ bot_debate_history = "".join(
712
+ st.session_state.bot_debate_history
 
 
 
 
 
 
713
  )
714
 
715
+ judgement_result = debate_judgement(
716
+ user_debate_history,
717
+ bot_debate_history
718
+ )
719
 
720
+ st.write("Debate Judgement Result")
721
+ st.write(judgement_result)
722
+
723
+ if judgement_result != "":
724
+ put_item(
725
+ table=dynamodb.Table('DEBO_evaluation'),
726
+ item={
727
+ 'user_id': st.session_state.user_id,
728
+ 'time_stamp': time_stamp,
729
+ 'judgement_text': judgement_result,
730
+ 'session_num': st.session_state.session_num,
731
+ }
732
+ )
733
+ st.success('Done!')
734
+ else:
735
+ st.write(st.session_state.judgement_result)
736
 
737
  with tab2:
738
+ st.header("Perfect Case")
739
+
740
+ perfect_case = perfect_case_selector(
741
+ st.session_state.debate_theme,
742
+ st.session_state.topic
743
+ )
744
+
745
+ st.write(perfect_case)
746
+
747
+
748
+ with tab3:
749
  st.header('Debate Analysis')
750
 
751
  # 유저의 history를 기반으로 발화량, 빈출 단어, 발화 습관 세 가지를 분석
 
756
  # 총 단어
757
  # 텍스트를 단어로 분할합니다.
758
  # 각 단어의 빈도를 계산합니다.
759
+
760
+ # 리스트를 문자열로 변환하고, 공백을 기준으로 단어를 분할합니다.
761
+ total_word_list = "".join(user_history).split()
762
+ total_word_count = len(total_word_list)
763
  #total_word_count = len(user_history.split())
764
  st.write("Total Word Count: ", total_word_count)
765
 
 
770
 
771
  # 2. 빈출 단어: 반복해서 사용하는 단어 리스트
772
  # 빈도 계산
773
+ frequency = Counter(total_word_list)
774
  # 가장 빈도가 높은 데이터 출력
775
+ most_common_data = frequency.most_common(5)
776
+
777
+ st.write("Most Common Words: ")
778
+ for word, count in most_common_data:
779
+ st.write(" - ", word, ":", count)
780
+
781
+ # print(most_common_data)
782
+ # st.write("Most Common Words: ", most_common_data)
783
 
784
  # 3. 발화 습관: 불필요한 언어습관(아, 음)
785
  # whisper preprocesser에서 주면
 
789
  st.write("Disfluency Counts: ", disfluency_counts)
790
 
791
  if total_word_count != "" and average_word_per_time != "" and disfluency_counts != "":
 
 
 
 
 
 
 
792
 
793
  put_item(
794
  table=dynamodb.Table('DEBO_debate_analysis'),
 
834
  # 전체, 유저, 봇 세 가지 옵션 중에 선택
835
  judgement_who = st.selectbox("Choose your debate theme", debate_themes)
836
 
837
+ if st.session_state.judgement_result == "":
838
+ with st.spinner('Wait for judgement result...'):
839
+ judgement_result = ""
 
 
 
 
 
 
840
 
841
+ user_debate_history = "".join(
842
+ st.session_state.user_debate_history
843
+ )
844
+ bot_debate_history = "".join(
845
+ st.session_state.bot_debate_history
846
  )
 
 
 
847
 
848
+ judgement_result = debate_judgement(
849
+ judgement_who,
850
+ user_debate_history,
851
+ bot_debate_history
 
 
 
 
 
852
  )
853
+
854
+ st.session_state.judgement_result = judgement_result
855
+
856
+ st.write("Debate Judgement Result")
857
+ st.write(judgement_result)
858
+
859
+ if judgement_result:
860
+ put_item(
861
+ table=dynamodb.Table('DEBO_evaluation'),
862
+ item={
863
+ 'user_id': st.session_state.user_id,
864
+ 'time_stamp': time_stamp,
865
+ 'judgement_text': judgement_result,
866
+ 'session_num': int(st.session_state.session_num),
867
+ }
868
+ )
869
+ st.success('Done!')
870
+ else:
871
+ st.write(st.session_state.judgement_result)
872
 
873
  with tab2:
874
  st.header('Debate Analysis')
bots/judgement_bot.py CHANGED
@@ -2,33 +2,13 @@ from modules.gpt_modules import gpt_call
2
  from langchain.prompts import PromptTemplate
3
 
4
  def debate_judgement(
5
- judgement_who,
6
  user_debate_history,
7
  bot_debate_history
8
  ):
9
-
10
- if judgement_who == 'User-Bot':
11
-
12
- judgement_prompt_preset = "\n".join([
13
- "!!Instruction!",
14
- "You are now the judge of this debate. Evaluate the debate according to the rules below.",
15
- "Rule 1. Decide between the USER and BOT.",
16
- "Rule 2. Summarize the debate as a whole and what each debater said.",
17
- "Rule 3. For each debater, explain what was persuasive and what made the differnce between winning and losing.",
18
- ])
19
-
20
- judgement_prompt = "\n".join([
21
- judgement_prompt_preset,
22
- "User: " + user_debate_history,
23
- "Bot: " + bot_debate_history,
24
- "Judgement must be logical with paragraphs.",
25
- "Do not show Rule",
26
- "Write judgement below.",
27
- "Judgement: "
28
- ])
29
-
30
- elif judgement_who == 'User':
31
-
32
  judgement_prompt_preset = "\n".join([
33
  "!!Instruction!",
34
  "You are now the judge of this debate. Evaluate the debate according to the rules below.",
@@ -45,24 +25,6 @@ def debate_judgement(
45
  "Judgement: "
46
  ])
47
 
48
- elif judgement_who == 'Bot':
49
-
50
- judgement_prompt_preset = "\n".join([
51
- "!!Instruction!",
52
- "You are now the judge of this debate. Evaluate the debate according to the rules below.",
53
- "Rule 1. Summarize the debate as a whole and each said.",
54
- "Rule 2. Explain what was persuasive and what made the differnce between winning and losing.",
55
- ])
56
-
57
- judgement_prompt = "\n".join([
58
- judgement_prompt_preset,
59
- "Bot: " + bot_debate_history,
60
- "Judgement must be logical with paragraphs.",
61
- "Do not show Rule",
62
- "Write judgement below.",
63
- "Judgement: "
64
- ])
65
-
66
- bot_response = gpt_call(judgement_prompt)
67
 
68
  return bot_response
 
2
  from langchain.prompts import PromptTemplate
3
 
4
  def debate_judgement(
 
5
  user_debate_history,
6
  bot_debate_history
7
  ):
8
+
9
+ if len(user_debate_history.split()) < 100:
10
+ bot_response = "Under the 100 words, evaluation is not possible."
11
+ else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  judgement_prompt_preset = "\n".join([
13
  "!!Instruction!",
14
  "You are now the judge of this debate. Evaluate the debate according to the rules below.",
 
25
  "Judgement: "
26
  ])
27
 
28
+ bot_response = gpt_call(judgement_prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  return bot_response
bots/perfect_case_bot.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+
4
+ def perfect_case_selector(debate_theme, topic):
5
+
6
+ if debate_theme == 'Education':
7
+ topic_list = [
8
+ "THBT college entrance examinations should accept students only on the basis of their academic performance in secondary education.",
9
+ "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.",
10
+ "THW abolish all requirements and evaluation criteria in higher education (i.e., attendance, exams, assignments)."
11
+ ]
12
+ elif debate_theme == 'Sports':
13
+ topic_list = [
14
+ "THBT having star players for team sports do more harm than good to the team.",
15
+ "THR the emphasis on winning a medal in the Olympics as a core symbol of success.",
16
+ "THP a world where sports serves purely entertainment purposes even at the expense of fair play."
17
+ ]
18
+ elif debate_theme == 'Religion':
19
+ topic_list = [
20
+ "THW, as a religious group/leader, cease attempts at increasing the number of believers and instead prioritize boosting loyalty amongst adherents to the religion.",
21
+ "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.",
22
+ "THW aggressively crackdown on megachurches."
23
+ ]
24
+ elif debate_theme == 'Justice':
25
+ topic_list = [
26
+ "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.",
27
+ "In the case a human destroys the robot beyond repair, THW charge murder instead of property damage.",
28
+ "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."
29
+ ]
30
+ elif debate_theme == 'Pandemic':
31
+ topic_list = [
32
+ "During a pandemic, THBT businesses that benefit from the pandemic should be additionally taxed.",
33
+ "THW nullify the effect of medical patents in cases of medical emergencies.",
34
+ "THW ban media content that denies the efficacy of the COVID-19 without substantial evidence."
35
+ ]
36
+ elif debate_theme == 'Politics':
37
+ topic_list = [
38
+ "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.",
39
+ "THW impose a cap on the property and income of politicians.",
40
+ "THW give the youth extra votes."
41
+ ]
42
+ elif debate_theme == 'Minority':
43
+ topic_list = [
44
+ "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.",
45
+ "THBT the LGBTQIA+ movement should denounce the existence of marriage as opposed to fighting for equal marriage rights.",
46
+ "THBT the LGBTQIA+ movement should condemn the consumption of movies and TV shows that cast straight actors/actresses in non-heterosexual identified roles."
47
+ ]
48
+ else:
49
+ topic_list = [
50
+ "THW remove all laws that relate to filial responsibilities.",
51
+ "THW require parents to receive approval from experts in relevant fields before making crucial decisions for their children.",
52
+ "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.",
53
+ "THBT any upper limits on prison sentences for particularly heinous crimes should be abolished.",
54
+ "THW require dating apps to anonymize profile pictures.",
55
+ "THW adopt a Pass/Fail grading system for students who suffer from mental health problems (e.g. depression, bipolar disorder, etc.).",
56
+ "THBT South Korean feminist movements should reject feminist icons that are adversarial and embody violence.",
57
+ "THBT freedom of speech should be considered obsolete.",
58
+ "THR the narrative that eccentric personalities are essential to create art.",
59
+ "THW allow parents of severely mentally disabled children to medically impede their children's physical growth.",
60
+ "THR the emphasis on longevity in relationships.",
61
+ "Assuming feasibility, THW choose to continuously relive the happiest moment of one’s life."
62
+ ]
63
+
64
+ perfect_case_result = "perfect_case_result"
65
+
66
+ return perfect_case_result