Spaces:
Runtime error
Runtime error
import gradio as gr | |
import random | |
import json | |
with open('species.json') as f: | |
lista = json.load(f) | |
def inicializar_preguntas(num_questions=30): | |
muestra_juego = random.sample(lista, num_questions) | |
questions = [] | |
for especie in muestra_juego: | |
correcta = especie['name'] | |
revision = True | |
while revision: | |
opciones = random.sample(lista, 3) | |
op_names = [op['name'] for op in opciones] | |
if correcta not in op_names: | |
op_names.append(correcta) | |
random.shuffle(op_names) | |
revision = False | |
questions.append({"image": especie['image_url'], "options": op_names, "answer": correcta}) | |
return questions | |
def check_question(option, ind, score, questions): | |
if ind == len(questions) - 1: | |
return f"Puntuación: {int(score/len(questions)*100)}%", None, None, None, score | |
if option == questions[ind]["answer"]: | |
score += 1 | |
texto_corr = "Correcto" | |
else: | |
texto_corr = f"Incorrecto\nLa respuesta correcta es: {questions[ind]['answer']}" | |
ind += 1 | |
image = gr.Image(value=questions[ind]["image"], height=300, width=300) | |
options = gr.Radio(choices=questions[ind]["options"]) | |
return texto_corr, ind, image, options, score | |
with gr.Blocks() as demo: | |
ind = gr.State(0) | |
score = gr.State(0) | |
questions = gr.State() | |
# Esta función se ejecuta cada vez que se carga la interfaz | |
def on_load(): | |
return {'questions': inicializar_preguntas(), 'ind': 0, 'score': 0} | |
image = gr.Image(height=300, width=300) | |
options = gr.Radio() | |
button = gr.Button("Siguiente pregunta") | |
output = gr.Textbox(label="Output Box") | |
def update_ui(questions, ind): | |
if questions and ind < len(questions): | |
image.update(value=questions[ind]["image"]) | |
options.update(choices=questions[ind]["options"]) | |
else: | |
image.update(value=None) | |
options.update(choices=[]) | |
button.click(fn=check_question, inputs=[options, ind, score, questions], outputs=[output, ind, image, options, score]) | |
demo.on("load")(update_ui) # Actualiza la UI al cargar basándose en las preguntas generadas | |
if __name__ == "__main__": | |
demo.launch(share=True) | |