Yoon-gu Hwang commited on
Commit
be55574
·
1 Parent(s): bcc2db5

button 리스트도 유저별 관리

Browse files
Files changed (1) hide show
  1. app.py +19 -18
app.py CHANGED
@@ -11,8 +11,6 @@ from collections import defaultdict
11
  wandb.login(key=os.environ['WANDB_KEY'])
12
  run = wandb.init(project="pokemon-quiz", entity="yoon-gu")
13
 
14
- random_buttons = [gr.Button(value=f"{name}") for name in ['1번', '2번', '3번', '4번']]
15
-
16
  with open('pokemon.json', 'r') as f:
17
  pokemons = json.load(f)
18
  pokemons_types = ["모든 타입"] + sorted(set([t for poke in pokemons for t in poke['types']]))
@@ -32,7 +30,7 @@ GEN_RANGE = {
32
 
33
  QUESTION_TEMPLATE = {"question": "다음 포켓몬의 이름은 뭘까요?![]({img_url})", "answer": "{name}"}
34
 
35
- def get_question_answer(pokemons_set):
36
  chosen = random.choice(pokemons_set)
37
  name = chosen['name'].replace("♀", "암컷").replace("♂", "수컷")
38
  image_path = chosen['image_path']
@@ -43,14 +41,15 @@ def get_question_answer(pokemons_set):
43
  candidates = random.choices([poke['name'] for poke in pokemons_set], k=3)
44
  candidates.append(a)
45
  random.shuffle(candidates)
46
- random_buttons = [gr.Button(value=f"{name}") for name in candidates]
47
- return q, a, random_buttons
48
 
49
  initial_info = {"done" : True,
50
  "score": 0, "count": 0,
51
  "best_score": 0, "best_time": float("inf"),
52
  "time": 0.0, "comment": "",
53
- "history": []}
 
54
 
55
  try:
56
  folder = run.use_artifact("settings:latest").download()
@@ -58,9 +57,6 @@ try:
58
  USERS = json.load(f)
59
  with open(os.path.join(folder, "info.json"), "r") as f:
60
  info = json.load(f)
61
- for user in USERS:
62
- if "history" not in info[user]:
63
- info[user]['history'] = []
64
  except:
65
  info = defaultdict(lambda : deepcopy(initial_info))
66
  USERS = ["김서현", "김우주", "Anonymous"]
@@ -126,7 +122,7 @@ with gr.Blocks() as demo:
126
  global random_buttons
127
  if done:
128
  if "퀴즈시작" == message.replace(" ", ""):
129
- q, a, random_buttons = get_question_answer(pokemons_set)
130
  bot_message = f"퀴즈를 시작합니다.\n{q}"
131
  info[user]['answer'] = a
132
  info[user]['done'] = False
@@ -137,18 +133,18 @@ with gr.Blocks() as demo:
137
  bot_message = "퀴즈를 시작하고 싶으시면, **퀴즈 시작** 버튼을 누르세요."
138
  else:
139
  if info[user]['answer'] == message:
140
- q, a, random_buttons = get_question_answer(pokemons_set)
141
  info[user]['answer'] = a
142
  info[user]['score'] += 1
143
  info[user]['count'] += 1
144
- bot_message = f"🎉정답입니다! 다음 문제입니다.\n{q}\n- 현재 점수: {info[user]['score']}점\n- 소요 시간: {time.time() - info[user]['time']:4.3f}초"
145
 
146
  elif "포기하기" == message.replace(" ", ""):
147
  bot_message = f"퀴즈를 강제 종료합니다."
148
  info[user]['done'] = True
149
  elif "문제 넘어가기" == message:
150
  info[user]['count'] += 1
151
- q, a = get_question_answer(pokemons_set)
152
  info[user]['answer'] = a
153
  bot_message = f"문제를 넘어갑니다. 다음문제입니다.\n{q}"
154
  else:
@@ -195,7 +191,7 @@ with gr.Blocks() as demo:
195
  else:
196
  btn = gr.Button(value="포기하기", label="퀴즈 중단")
197
 
198
-
199
  return btn, info[user]['history'], md, *random_buttons
200
 
201
  play.click(respond,
@@ -217,8 +213,6 @@ with gr.Blocks() as demo:
217
  new_dropdown = gr.Dropdown(sorted(USERS), value=rs, label="사용자", info="당신은 누구신가요?", allow_custom_value=True)
218
  return new_dropdown
219
 
220
- user.blur(rs_change, user, user)
221
-
222
  def update_table(user):
223
  leader_board = sorted(info.items(), key=lambda x: (x[1]['best_score'], -x[1]['best_time']), reverse=True)
224
  lbdf = pd.DataFrame([dict(**a[1], name=a[0]) for a in leader_board])
@@ -231,10 +225,17 @@ with gr.Blocks() as demo:
231
  else:
232
  btn = gr.Button(value="포기하기", label="퀴즈 중단")
233
 
234
- return btn, md, gr.Dropdown(USERS, value=user, label="사용자", info="당신은 누구신가요?", allow_custom_value=True), info[user]['history']
 
 
 
 
 
 
 
235
  demo.load(update_table,
236
  inputs=user,
237
- outputs=[play, leader_board, user, chatbot])
238
 
239
  demo.queue(concurrency_count=3)
240
  demo.launch()
 
11
  wandb.login(key=os.environ['WANDB_KEY'])
12
  run = wandb.init(project="pokemon-quiz", entity="yoon-gu")
13
 
 
 
14
  with open('pokemon.json', 'r') as f:
15
  pokemons = json.load(f)
16
  pokemons_types = ["모든 타입"] + sorted(set([t for poke in pokemons for t in poke['types']]))
 
30
 
31
  QUESTION_TEMPLATE = {"question": "다음 포켓몬의 이름은 뭘까요?![]({img_url})", "answer": "{name}"}
32
 
33
+ def get_question_answer(pokemons_set, user):
34
  chosen = random.choice(pokemons_set)
35
  name = chosen['name'].replace("♀", "암컷").replace("♂", "수컷")
36
  image_path = chosen['image_path']
 
41
  candidates = random.choices([poke['name'] for poke in pokemons_set], k=3)
42
  candidates.append(a)
43
  random.shuffle(candidates)
44
+ info[user]['candidates'] = candidates
45
+ return q, a
46
 
47
  initial_info = {"done" : True,
48
  "score": 0, "count": 0,
49
  "best_score": 0, "best_time": float("inf"),
50
  "time": 0.0, "comment": "",
51
+ "history": [],
52
+ "candidates": ['1번', '2번', '3번', '4번']}
53
 
54
  try:
55
  folder = run.use_artifact("settings:latest").download()
 
57
  USERS = json.load(f)
58
  with open(os.path.join(folder, "info.json"), "r") as f:
59
  info = json.load(f)
 
 
 
60
  except:
61
  info = defaultdict(lambda : deepcopy(initial_info))
62
  USERS = ["김서현", "김우주", "Anonymous"]
 
122
  global random_buttons
123
  if done:
124
  if "퀴즈시작" == message.replace(" ", ""):
125
+ q, a = get_question_answer(pokemons_set, user)
126
  bot_message = f"퀴즈를 시작합니다.\n{q}"
127
  info[user]['answer'] = a
128
  info[user]['done'] = False
 
133
  bot_message = "퀴즈를 시작하고 싶으시면, **퀴즈 시작** 버튼을 누르세요."
134
  else:
135
  if info[user]['answer'] == message:
136
+ q, a = get_question_answer(pokemons_set, user)
137
  info[user]['answer'] = a
138
  info[user]['score'] += 1
139
  info[user]['count'] += 1
140
+ bot_message = f"🎉정답입니다! 다음 문제입니다.\n{q}\n- 현재 점수: {info[user]['score']:3.1f}점\n- 소요 시간: {time.time() - info[user]['time']:4.3f}초"
141
 
142
  elif "포기하기" == message.replace(" ", ""):
143
  bot_message = f"퀴즈를 강제 종료합니다."
144
  info[user]['done'] = True
145
  elif "문제 넘어가기" == message:
146
  info[user]['count'] += 1
147
+ q, a = get_question_answer(pokemons_set, user)
148
  info[user]['answer'] = a
149
  bot_message = f"문제를 넘어갑니다. 다음문제입니다.\n{q}"
150
  else:
 
191
  else:
192
  btn = gr.Button(value="포기하기", label="퀴즈 중단")
193
 
194
+ random_buttons = [gr.Button(value=c) for c in info[user]['candidates']]
195
  return btn, info[user]['history'], md, *random_buttons
196
 
197
  play.click(respond,
 
213
  new_dropdown = gr.Dropdown(sorted(USERS), value=rs, label="사용자", info="당신은 누구신가요?", allow_custom_value=True)
214
  return new_dropdown
215
 
 
 
216
  def update_table(user):
217
  leader_board = sorted(info.items(), key=lambda x: (x[1]['best_score'], -x[1]['best_time']), reverse=True)
218
  lbdf = pd.DataFrame([dict(**a[1], name=a[0]) for a in leader_board])
 
225
  else:
226
  btn = gr.Button(value="포기하기", label="퀴즈 중단")
227
 
228
+ random_buttons = [gr.Button(value=c) for c in info[user]['candidates']]
229
+ return btn, md, gr.Dropdown(USERS, value=user, label="사용자", info="당신은 누구신가요?", allow_custom_value=True), info[user]['history'], *random_buttons
230
+
231
+ user.blur(rs_change, user, user)
232
+ user.select(update_table,
233
+ inputs=user,
234
+ outputs=[play, leader_board, user, chatbot, button1, button2, button3, button4])
235
+
236
  demo.load(update_table,
237
  inputs=user,
238
+ outputs=[play, leader_board, user, chatbot, button1, button2, button3, button4])
239
 
240
  demo.queue(concurrency_count=3)
241
  demo.launch()