math-quiz / app.py
yoon-gu's picture
Update app.py
ad7ae80
raw
history blame
3.33 kB
import gradio as gr
import pandas as pd
import random
import json
with open('pokemon.json', 'r') as f:
pokemons = json.load(f)
pokemons_types = ["λͺ¨λ“  νƒ€μž…"] + sorted(set([t for poke in pokemons for t in poke['types']]))
df = pd.DataFrame(pokemons)
GEN_RANGE = {
"λͺ¨λ“  μ„ΈλŒ€": [1, 1017],
"1μ„ΈλŒ€": [1, 151],
"2μ„ΈλŒ€": [152, 251],
"3μ„ΈλŒ€": [252, 386],
"4μ„ΈλŒ€": [387, 493],
"5μ„ΈλŒ€": [494, 649],
"6μ„ΈλŒ€": [650, 721],
"7μ„ΈλŒ€": [722, 809],
"8μ„ΈλŒ€": [810, 905],
"9μ„ΈλŒ€": [906, 1017]
}
QUESTION_TEMPLATE = {"question": "λ‹€μŒ 포켓λͺ¬μ˜ 이름은 λ­˜κΉŒμš”?![]({img_url})", "answer": "{name}"}
def get_question_answer(pokemons_set):
chosen = random.choice(pokemons_set)
name = chosen['name']
image_path = chosen['image_path']
answer.value = QUESTION_TEMPLATE['answer'].format(name=name)
img_url = f"https://huggingface.co/spaces/yoon-gu/pokemon/resolve/main/{image_path}"
q = QUESTION_TEMPLATE["question"].format(img_url=img_url)
a = QUESTION_TEMPLATE['answer'].format(name=name)
return q, a
MD = """# 포켓λͺ¬ ν€΄μ¦ˆ
"""
with gr.Blocks() as demo:
quiz_start = gr.State(value=False)
score = gr.State(value=0)
answer = gr.State(value="")
with gr.Row():
with gr.Column():
gr.Markdown(MD)
with gr.Column():
with gr.Row():
generation = gr.Dropdown(
[f"{k}μ„ΈλŒ€" for k in range(1, 10)] + ["λͺ¨λ“  μ„ΈλŒ€"], value="1μ„ΈλŒ€", label="포켓λͺ¬ μ„ΈλŒ€", info="μ›ν•˜λŠ” 포켓λͺ¬ μ„ΈλŒ€λ₯Ό μ„ νƒν•˜μ„Έμš”."
)
poke_types = gr.Dropdown(
pokemons_types, value="λͺ¨λ“  νƒ€μž…", label="포켓λͺ¬ νƒ€μž…", info="μ›ν•˜λŠ” 포켓λͺ¬ νƒ€μž…μ„ μ„ νƒν•˜μ„Έμš”."
)
chatbot = gr.Chatbot(bubble_full_width=False)
msg = gr.Textbox(value="ν€΄μ¦ˆ μ‹œμž‘")
clear = gr.ClearButton([msg, chatbot, quiz_start])
def respond(gen, types, message, chat_history, request: gr.Request):
start, end = GEN_RANGE[gen]
sdf = df[start:end]
pokemons_set = sdf[sdf['types'].apply(lambda x: (types in x)) | (types == "λͺ¨λ“  νƒ€μž…")]
pokemons_set = pokemons_set.to_dict("records")
if "ν€΄μ¦ˆ μ‹œμž‘" == message:
quiz_start.value = True
if not quiz_start.value:
if "ν€΄μ¦ˆ μ‹œμž‘" == message:
q, a = get_question_answer(pokemons_set)
bot_message = f"ν€΄μ¦ˆλ₯Ό μ‹œμž‘ν•©λ‹ˆλ‹€.\n{q}"
answer.value = a
quiz_start.value = True
else:
bot_message = "ν€΄μ¦ˆλ₯Ό μ‹œμž‘ν•˜κ³  μ‹ΆμœΌμ‹œλ©΄, **ν€΄μ¦ˆ μ‹œμž‘**이라고 λ§μ”€ν•΄μ£Όμ„Έμš”."
else:
if answer.value == message:
q, a = get_question_answer(pokemons_set)
answer.value = a
bot_message = f"πŸŽ‰μ •λ‹΅μž…λ‹ˆλ‹€! λ‹€μŒ λ¬Έμ œμž…λ‹ˆλ‹€.\n{q}"
else:
bot_message = f"***{message}***!? 🧐 λ‹€μ‹œ ν•œλ²ˆ μƒκ°ν•΄λ³΄μ„Έμš”."
chat_history.append((message, bot_message))
return "", chat_history
msg.submit(respond, [generation, poke_types, msg, chatbot], [msg, chatbot])
demo.queue(concurrency_count=3)
demo.launch()