gaeunseo commited on
Commit
e3a3cf7
·
verified ·
1 Parent(s): 43769dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -43
app.py CHANGED
@@ -1,66 +1,103 @@
1
  import gradio as gr
2
- import pandas as pd
3
  from datasets import load_dataset
4
  import random
5
-
6
- # 데이터셋 불러오기 및 전처리
7
- dataset = load_dataset("gaeunseo/Taskmaster_sample_data", split='train')
8
- df = dataset.to_pandas()
9
-
10
- # 전역 변수 선언
11
- statement = ""
12
-
13
- def update_statement(value):
14
- global statement
15
- statement = value
16
- return statement
17
 
18
  def load_random_conversations():
19
- # 'used'가 False인 그룹 필터링
20
- unused_groups = df[df['used'] == False].groupby('conversation_id')
 
 
 
 
 
 
 
 
 
 
21
 
22
- # 조건에 맞는 conversation_id 리스트
23
- valid_conversation_ids = [cid for cid, group in unused_groups if len(group) >= 2]
24
 
25
- if not valid_conversation_ids:
26
- return "No available conversation", "No available conversation"
27
 
28
- # 랜덤으로 하나의 conversation_id 선택
29
- selected_id = random.choice(valid_conversation_ids)
30
 
31
- # 선택된 그룹에서 개의 행을 랜덤 선택
32
- selected_group = df[df['conversation_id'] == selected_id]
33
- selected_conversations = selected_group.sample(2)
 
 
 
 
 
 
 
 
34
 
35
- # 선택된 대화 텍스트 반환
36
- conversation_A = selected_conversations.iloc[0]['text']
37
- conversation_B = selected_conversations.iloc[1]['text']
 
 
 
 
38
 
39
- return conversation_A, conversation_B
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  with gr.Blocks() as demo:
42
- # 개의 대화창을 좌우에 배치합니다.
43
  with gr.Row():
44
- conversation_A = gr.Textbox(label="Conversation A", placeholder="Enter conversation A here...", lines=10)
45
- conversation_B = gr.Textbox(label="Conversation B", placeholder="Enter conversation B here...", lines=10)
 
 
 
 
46
 
47
- # 4개의 버튼을 행에 배치합니다.
48
  with gr.Row():
49
  btn_both_good = gr.Button("Both good") # "둘 다 좋음" → "BG"
50
- btn_a_better = gr.Button("A is better") # "A가 더 좋음" → "AG"
51
- btn_b_better = gr.Button("B is better") # "B가 더 좋음" → "BG"
52
- btn_both_bad = gr.Button("Both not good") # "둘 다 별로임" → "BB"
53
 
54
- # 선택된 statement 값을 보여주기 위한 출력 텍스트박스 (옵션)
55
  statement_output = gr.Textbox(label="Selected Statement", value="", interactive=False)
56
 
57
- # 대화를 불러오는 버튼
58
- load_conversations_btn = gr.Button("Load Random Conversations")
59
-
60
- # 대화 불러오기 버튼 클릭 시 대화 상자 업데이트
61
- load_conversations_btn.click(fn=load_random_conversations, inputs=[], outputs=[conversation_A, conversation_B])
62
-
63
- # 각 버튼 클릭 시 update_statement 함수를 호출하여 statement 값을 업데이트합니다.
64
  btn_both_good.click(fn=lambda: update_statement("BG"), inputs=[], outputs=statement_output)
65
  btn_a_better.click(fn=lambda: update_statement("AG"), inputs=[], outputs=statement_output)
66
  btn_b_better.click(fn=lambda: update_statement("BG"), inputs=[], outputs=statement_output)
 
1
  import gradio as gr
 
2
  from datasets import load_dataset
3
  import random
4
+ import re
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  def load_random_conversations():
7
+ """
8
+ 데이터셋 'gaeunseo/Taskmaster_sample_data' train split에서
9
+ conversation_id별로 그룹화한 후, 모든 행의 used가 False인 그룹만 남겨,
10
+ 이 중 랜덤하게 2개 그룹을 선택하여 각 대화의 모든 utterance를 줄바꿈으로 연결한 문자열 두 개를 반환.
11
+ """
12
+ ds = load_dataset("gaeunseo/Taskmaster_sample_data")["train"]
13
+
14
+ # conversation_id 별로 그룹화
15
+ groups = {}
16
+ for row in ds:
17
+ cid = row["conversation_id"]
18
+ groups.setdefault(cid, []).append(row)
19
 
20
+ # 그룹 모든 행의 used가 False인 그룹만 선택
21
+ valid_groups = [grp for grp in groups.values() if all(not row["used"] for row in grp)]
22
 
23
+ if len(valid_groups) < 2:
24
+ return "Not enough unused conversations", "Not enough unused conversations"
25
 
26
+ # 유효한 그룹 랜덤하게 2개 선택
27
+ selected_groups = random.sample(valid_groups, 2)
28
 
29
+ # 그룹의 모든 utterance를 이어붙임
30
+ conv_A = "\n".join(row["utterance"] for row in selected_groups[0])
31
+ conv_B = "\n".join(row["utterance"] for row in selected_groups[1])
32
+
33
+ return conv_A, conv_B
34
+
35
+ def format_chat(conv_text):
36
+ """
37
+ conv_text 문자열을 [turn]과 [BC] 토큰을 기준으로 분할한 후,
38
+ 첫 번째 발화는 사람(사용자), 두 번째 발화는 AI의 응답으로 간주하여
39
+ gr.Chatbot 컴포넌트에서 사용하는 (user_message, ai_message) 튜플 리스트로 변환.
40
 
41
+ - 사람(사용자) 메시지: 오른쪽 말풍선, 메시지 끝에 "🧑" 이모티콘 추가
42
+ - AI 메시지: 왼쪽 말풍선, 메시지 앞에 "🤖" 이모티콘 추가
43
+ """
44
+ # [turn]와 [BC]를 구분자로 사용하여 발화 분할
45
+ utterances = re.split(r'\[turn\]|\[BC\]', conv_text)
46
+ # 공백 제거 및 빈 문자열 제거
47
+ utterances = [utt.strip() for utt in utterances if utt.strip()]
48
 
49
+ chat = []
50
+ # 번갈아 등장한다고 가정 (첫 번째: 사람, 두 번째: AI, ...)
51
+ for i in range(0, len(utterances), 2):
52
+ # 첫 번째 발화 → 사람 (오른쪽 정렬: gr.Chatbot에서 사용자 메시지는 기본적으로 오른쪽에 표시됨)
53
+ human = utterances[i] + " 🧑"
54
+ ai = ""
55
+ if i + 1 < len(utterances):
56
+ # 두 번째 발화 → AI (왼쪽 정렬: gr.Chatbot에서 봇 메시지는 기본적으로 왼쪽에 표시됨)
57
+ ai = "🤖 " + utterances[i + 1]
58
+ chat.append((human, ai))
59
+ return chat
60
+
61
+ def load_and_format_conversations():
62
+ """
63
+ 데이터셋에서 랜덤하게 두 대화 문자열을 가져온 후, 각각 format_chat()을 통해
64
+ 채팅 인터페이스에 맞게 변환하여 반환.
65
+ """
66
+ conv_A, conv_B = load_random_conversations()
67
+ # 에러 메시지인 경우 그대로 반환
68
+ if conv_A.startswith("Not enough"):
69
+ return conv_A, conv_B
70
+ return format_chat(conv_A), format_chat(conv_B)
71
+
72
+ # 평가 버튼 클릭 시 업데이트할 전역 변수
73
+ statement = ""
74
+
75
+ def update_statement(val):
76
+ global statement
77
+ statement = val
78
+ return statement
79
 
80
  with gr.Blocks() as demo:
81
+ # 상단: 좌우에 각각 채팅 인터페이스 배치 (Conversation A와 Conversation B)
82
  with gr.Row():
83
+ chat_A = gr.Chatbot(label="Conversation A")
84
+ chat_B = gr.Chatbot(label="Conversation B")
85
+
86
+ # "Load Random Conversations" 버튼을 눌러 데이터셋에서 대화를 불러오고 채팅 인터페이스에 표시
87
+ load_btn = gr.Button("Load Random Conversations")
88
+ load_btn.click(fn=load_and_format_conversations, inputs=[], outputs=[chat_A, chat_B])
89
 
90
+ # 하단: 평가 버튼 4개 배치
91
  with gr.Row():
92
  btn_both_good = gr.Button("Both good") # "둘 다 좋음" → "BG"
93
+ btn_a_better = gr.Button("A is better") # "A가 더 좋음" → "AG"
94
+ btn_b_better = gr.Button("B is better") # "B가 더 좋음" → "BG"
95
+ btn_both_bad = gr.Button("Both not good") # "둘 다 별로임" → "BB"
96
 
97
+ # 선택된 평가값(statement)을 보여주는 텍스트박스
98
  statement_output = gr.Textbox(label="Selected Statement", value="", interactive=False)
99
 
100
+ # 평가 버튼 클릭 시 해당 상태값 업데이트
 
 
 
 
 
 
101
  btn_both_good.click(fn=lambda: update_statement("BG"), inputs=[], outputs=statement_output)
102
  btn_a_better.click(fn=lambda: update_statement("AG"), inputs=[], outputs=statement_output)
103
  btn_b_better.click(fn=lambda: update_statement("BG"), inputs=[], outputs=statement_output)