File size: 2,297 Bytes
b152d54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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()

    @gr.on("load")  # 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)