te commited on
Commit
b152d54
·
1 Parent(s): d303813

first commit

Browse files
Files changed (12) hide show
  1. .gitignore +3 -0
  2. create_dbs.py +73 -0
  3. main.py +142 -0
  4. prueba_html_gradio.py +20 -0
  5. quiz.py +66 -0
  6. reload_test.py +26 -0
  7. scrapper.py +77 -0
  8. scrapper2.py +38 -0
  9. species.json +0 -0
  10. test.py +36 -0
  11. test2.py +142 -0
  12. test_streamlit.py +16 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ trash
2
+ .conda
3
+ flagged
create_dbs.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+ import re
4
+ import json
5
+
6
+ regionCode = 'CO-ANT'
7
+ ebird_api_key = 'dj45pbobk3g5'
8
+
9
+
10
+ def get_region_species_list():
11
+ url = f'https://api.ebird.org/v2/product/spplist/{regionCode}'
12
+ headers = {'x-ebirdapitoken':ebird_api_key}
13
+ response = requests.get(url, headers=headers)
14
+ if response.status_code == 200:
15
+ data = response.json()
16
+ return data
17
+ else:
18
+ return None
19
+
20
+ def get_species_name(taxonCode):
21
+ url = f'https://api.ebird.org/v2/ref/taxonomy/ebird?species={taxonCode}&fmt=json'
22
+ response = requests.get(url)
23
+ if response.status_code == 200:
24
+ data = response.json()
25
+ return data[0]['sciName']
26
+ else:
27
+ return None
28
+
29
+ def get_image_url(regionCode, taxonCode):
30
+ # url = f"https://search.macaulaylibrary.org/catalog?regionCode={regionCode}&taxonCode={taxonCode}&sort=rating_rank_desc&mediaType=photo"
31
+ url = f"https://search.macaulaylibrary.org/catalog?taxonCode={taxonCode}&sort=rating_rank_desc&mediaType=photo"
32
+
33
+ response = requests.get(url)
34
+ if response.status_code == 200:
35
+ soup = BeautifulSoup(response.content, 'html.parser')
36
+ script_str = soup.find_all('script')
37
+ # enlace = soup.find('meta', {'property': 'og:image'})['content']
38
+ # print('enlace: ', enlace)
39
+ match = re.search(r'assetId:(\d+),', str(script_str))
40
+ if match:
41
+ asset_id = match.group(1)
42
+ enlace = f"https://cdn.download.ams.birds.cornell.edu/api/v1/asset/{asset_id}"
43
+ print(enlace)
44
+ return enlace
45
+ else:
46
+ return None
47
+ else:
48
+ return None
49
+
50
+
51
+ species = []
52
+
53
+ species_codes = get_region_species_list()
54
+ print('len of species codes: ', len(species_codes))
55
+ if species_codes:
56
+ for ind, species_code in enumerate(species_codes):
57
+ print(ind + 1, 'of', len(species_codes))
58
+ species_name = get_species_name(species_code)
59
+ if not species_code:
60
+ print('error with: ', species_code)
61
+
62
+ image_url = get_image_url(regionCode, species_code)
63
+ if not image_url:
64
+ print('error with image url: ', species_code)
65
+
66
+ species.append({'code':species_code, 'name':species_name, 'image_url':image_url})
67
+
68
+ # save to json:
69
+
70
+ with open('species.json', 'w') as f:
71
+ json.dump(species, f)
72
+
73
+ print('len of species: ', len(species))
main.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ import json
4
+
5
+ with open('species.json') as f:
6
+ lista = json.load(f)
7
+
8
+
9
+
10
+ def inicializar_preguntas():
11
+ num_questions = 20
12
+
13
+ muestra_juego = random.sample(lista, num_questions)
14
+
15
+ questions = []
16
+
17
+ for especie in muestra_juego:
18
+ correcta = especie['name']
19
+ revision = True
20
+ while revision:
21
+ opciones = random.sample(lista, 3)
22
+ op_names = [op['name'] for op in opciones]
23
+ if not correcta in op_names:
24
+ op_names.append(correcta)
25
+ random.shuffle(op_names)
26
+ revision = False
27
+
28
+ # posicion_ultima_barra = especie['image_url'].rfind('/')
29
+ # enlace_recortado = especie['image_url'][:posicion_ultima_barra]
30
+ questions.append({"image": especie['image_url'], "options": op_names, "answer": correcta})
31
+ return questions
32
+
33
+ def check_question(option, ind, score, questions):
34
+ try:
35
+ questions = questions.value
36
+ except:
37
+ questions = questions
38
+
39
+ try:
40
+ score = score.value
41
+ except:
42
+ score = score
43
+
44
+ try:
45
+ ind = ind.value
46
+ except:
47
+ ind = ind
48
+
49
+
50
+
51
+ if ind == len(questions) - 1:
52
+ # # _, ind, score, image, options, _ = fin_preguntas()# restart_quiz()
53
+ # questions_list = inicializar_preguntas()
54
+ # questions = gr.State(questions_list)
55
+ # #ind = gr.State(0)
56
+ image = gr.Image(height=300, width=300)
57
+ options = gr.Radio() #choices=questions[ind.value]["options"])
58
+
59
+ if option == questions[ind]["answer"]:
60
+ score += 1
61
+ texto_corr = "Correcto"
62
+ else:
63
+ texto_corr = "Incorrecto\nLa respuesta correcta es: " + questions[ind]["answer"]
64
+
65
+ # try:
66
+ return texto_corr, ind, score, image, options, f"Terminó el quiz\nTuviste {score} de {ind} preguntas correctas\nScore: {int(score/len(questions)*100)}\nReinicie para empezar de nuevo"
67
+ # except:
68
+ # return texto_corr, ind, score, image, options, f"Terminó el quiz\nScore: {int(score.value/len(questions)*100)}\nReinicie para empezar de nuevo"
69
+
70
+
71
+
72
+ if option == questions[ind]["answer"]:
73
+ score += 1
74
+ texto_corr = "Correcto"
75
+ else:
76
+ texto_corr = "Incorrecto\nLa respuesta correcta es: " + questions[ind]["answer"]
77
+
78
+ ind += 1
79
+ image = gr.Image(value=questions[ind]["image"], height=300, width=300)
80
+ options = gr.Radio(choices=questions[ind]["options"])
81
+
82
+ return texto_corr, ind, score, image, options, f"Llevas: {score} de {ind} preguntas"
83
+
84
+ def restart_quiz():
85
+ score = gr.State(0)
86
+ questions_list = inicializar_preguntas()
87
+ questions = gr.State(questions_list)
88
+ try:
89
+ questions = questions.value
90
+ except:
91
+ questions = questions
92
+
93
+ try:
94
+ score = score.value
95
+ except:
96
+ score = score
97
+
98
+
99
+ # questions, ind, image, options = inicializar_preguntas()
100
+
101
+ ind = gr.State(0)
102
+ try:
103
+ ind = ind.value
104
+ except:
105
+ ind = ind
106
+
107
+ image = gr.Image(value=questions[ind]["image"], height=300, width=300)
108
+ options = gr.Radio(choices=questions[ind]["options"])
109
+
110
+ output = ""
111
+ return output, ind, score, image, options, f"", questions
112
+
113
+ def fin_preguntas():
114
+ # score = gr.State(0)
115
+ questions_list = inicializar_preguntas()
116
+ questions = gr.State(questions_list)
117
+ # questions, ind, image, options = inicializar_preguntas()
118
+
119
+ return "Fin", ind, score, image, options, f"Score: {int(score.value/len(questions)*100)}"
120
+
121
+
122
+ with gr.Blocks() as demo:
123
+ # Preguntas al azar
124
+ questions_list = inicializar_preguntas()
125
+ questions = gr.State(questions_list)
126
+ # Variables
127
+ score = gr.State(0)
128
+ ind = gr.State(0)
129
+ # Componentes
130
+ image = gr.Image(value=questions.value[ind.value]["image"], height=300, width=300)
131
+ options = gr.Radio(choices=questions.value[ind.value]["options"])
132
+ button = gr.Button("Siguiente pregunta")
133
+ output = gr.Textbox(label="Output Box")
134
+ output_score = gr.Textbox(label="Output Box")
135
+ restart_button = gr.Button("Restart")
136
+ # Funciones
137
+ button.click(fn=check_question, inputs=[options, ind, score, questions], outputs=[output, ind, score, image, options, output_score])
138
+ restart_button.click(fn=restart_quiz, inputs=[], outputs=[output, ind, score, image, options, output_score, questions])
139
+
140
+
141
+ if __name__ == "__main__":
142
+ demo.launch(share=True)
prueba_html_gradio.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ title = "test"
4
+
5
+ def inference(text):
6
+ html = (
7
+ "<div >"
8
+ "<img src='file/lion.jpg' alt='image One'>"
9
+ + "</div>"
10
+ )
11
+ return html
12
+
13
+ gr.Interface(
14
+ inference,
15
+ gr.inputs.Textbox(placeholder="Enter sentence here..."),
16
+ outputs=["html"],
17
+ title=title,
18
+ allow_flagging="never",
19
+
20
+ ).launch(enable_queue=True)
quiz.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ import json
4
+
5
+ with open('species.json') as f:
6
+ lista = json.load(f)
7
+
8
+ def inicializar_preguntas(num_questions=30):
9
+ muestra_juego = random.sample(lista, num_questions)
10
+ questions = []
11
+ for especie in muestra_juego:
12
+ correcta = especie['name']
13
+ revision = True
14
+ while revision:
15
+ opciones = random.sample(lista, 3)
16
+ op_names = [op['name'] for op in opciones]
17
+ if correcta not in op_names:
18
+ op_names.append(correcta)
19
+ random.shuffle(op_names)
20
+ revision = False
21
+ questions.append({"image": especie['image_url'], "options": op_names, "answer": correcta})
22
+ return questions
23
+
24
+ def check_question(option, ind, score, questions):
25
+ if ind == len(questions) - 1:
26
+ return f"Puntuación: {int(score/len(questions)*100)}%", None, None, None, score
27
+
28
+ if option == questions[ind]["answer"]:
29
+ score += 1
30
+ texto_corr = "Correcto"
31
+ else:
32
+ texto_corr = f"Incorrecto\nLa respuesta correcta es: {questions[ind]['answer']}"
33
+
34
+ ind += 1
35
+ image = gr.Image(value=questions[ind]["image"], height=300, width=300)
36
+ options = gr.Radio(choices=questions[ind]["options"])
37
+
38
+ return texto_corr, ind, image, options, score
39
+
40
+ with gr.Blocks() as demo:
41
+ ind = gr.State(0)
42
+ score = gr.State(0)
43
+ questions = gr.State()
44
+
45
+ @gr.on("load") # Esta función se ejecuta cada vez que se carga la interfaz
46
+ def on_load():
47
+ return {'questions': inicializar_preguntas(), 'ind': 0, 'score': 0}
48
+
49
+ image = gr.Image(height=300, width=300)
50
+ options = gr.Radio()
51
+ button = gr.Button("Siguiente pregunta")
52
+ output = gr.Textbox(label="Output Box")
53
+
54
+ def update_ui(questions, ind):
55
+ if questions and ind < len(questions):
56
+ image.update(value=questions[ind]["image"])
57
+ options.update(choices=questions[ind]["options"])
58
+ else:
59
+ image.update(value=None)
60
+ options.update(choices=[])
61
+
62
+ button.click(fn=check_question, inputs=[options, ind, score, questions], outputs=[output, ind, image, options, score])
63
+ demo.on("load")(update_ui) # Actualiza la UI al cargar basándose en las preguntas generadas
64
+
65
+ if __name__ == "__main__":
66
+ demo.launch(share=True)
reload_test.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+
4
+ def generate_random_number():
5
+ """
6
+ Generates a random number between 1 and 100.
7
+ Takes a dummy argument to comply with Gradio's expectations when triggered by a button.
8
+ """
9
+ return random.randint(1, 100)
10
+
11
+ # The 'Button' component triggers the action. In Gradio 4.5.0, components are more streamlined,
12
+ # and you might not need to specify the input component type as explicitly.
13
+ # Here, the button is directly linked to the action function.
14
+ # Note: Unlike previous versions, if your function expects an argument from an input component,
15
+ # you must ensure the function can accept it, even if the input is not used.
16
+ # Hence, the dummy parameter in 'generate_random_number' function.
17
+
18
+ with gr.Blocks() as demo:
19
+ gr.Markdown("# Random Number Generator")
20
+ gr.Markdown("Click the button to generate a new random number.")
21
+ button = gr.Button("Refresh Number")
22
+ output = gr.Number(label="Random Number")
23
+
24
+ button.click(fn=generate_random_number, inputs=[], outputs=output)
25
+
26
+ demo.launch()
scrapper.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+ import re
4
+
5
+
6
+ def get_image_url(regionCode, taxonCode):
7
+ url = f"https://search.macaulaylibrary.org/catalog?regionCode={regionCode}&taxonCode={taxonCode}&sort=rating_rank_desc&mediaType=photo"
8
+ response = requests.get(url)
9
+ if response.status_code == 200:
10
+ soup = BeautifulSoup(response.content, 'html.parser')
11
+ script_str = soup.find_all('script')
12
+ match = re.search(r'assetId:(\d+),', str(script_str))
13
+ if match:
14
+ asset_id = match.group(1)
15
+ return asset_id
16
+ else:
17
+ return None
18
+ else:
19
+ return None
20
+
21
+
22
+ # Set the URL of the webpage to be scraped
23
+
24
+ url = "https://search.macaulaylibrary.org/catalog?regionCode=CO-ANT&taxonCode=bertin1&sort=rating_rank_desc&mediaType=photo"
25
+
26
+ # Send a GET request to the URL
27
+ response = requests.get(url)
28
+
29
+ # Check if the request was successful (status code 200)
30
+ if response.status_code == 200:
31
+ # print('ok')
32
+ # Parse the HTML content
33
+ soup = BeautifulSoup(response.content, 'html.parser')
34
+ script_str = soup.find_all('script')
35
+ with open('prueba4.html', 'w', encoding='utf-8') as f:
36
+ f.write(str(script_str))
37
+
38
+ # Extract the image URL from the HTML content)
39
+ # enlace = soup.find('meta', {'property': 'og:image'})['content']
40
+ enlace = soup.find_all('div', {'id': 'ResultsGallery-row'})
41
+
42
+
43
+ # Imprimir el enlace
44
+ print(enlace)
45
+
46
+ # with open('prueba2.html', 'w', encoding='utf-8') as f:
47
+ # f.write(str(soup))
48
+
49
+ #print(soup.prettify())
50
+ # prueba = soup.find_all('div', {'class': 'ResultsGallery'})
51
+ prueba = soup.find_all('script')
52
+ # print(str(prueba))
53
+
54
+
55
+ match = re.search(r'assetId:(\d+),', str(prueba))
56
+
57
+ if match:
58
+ asset_id = match.group(1)
59
+ print(f"Asset ID: {asset_id}")
60
+ else:
61
+ print("Asset ID not found.")
62
+
63
+ # ---------------
64
+
65
+
66
+ # with open('prueba.html', 'w', encoding='utf-8') as f:
67
+ # f.write(str(prueba))
68
+
69
+ # # Now you can use BeautifulSoup to extract information from the HTML
70
+ # # For example, let's extract all image URLs
71
+ # image_urls = [img['src'] for img in soup.find_all('data-asset-id')]
72
+
73
+ # # Print the extracted image URLs
74
+ # for i, url in enumerate(image_urls, start=1):
75
+ # print(f"Image {i}: {url}")
76
+ else:
77
+ print(f"Failed to retrieve the webpage. Status code: {response.status_code}")
scrapper2.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from selenium import webdriver
2
+ from bs4 import BeautifulSoup
3
+
4
+ url = "https://search.macaulaylibrary.org/catalog?regionCode=CO-ANT&taxonCode=bltfly1&sort=rating_rank_desc&mediaType=photo"
5
+
6
+ # Set up the ChromeDriver (you need to have ChromeDriver installed and its path added to your system PATH)
7
+ driver = webdriver.Chrome()
8
+
9
+ # Load the webpage
10
+ driver.get(url)
11
+
12
+ # Get the page source after the dynamic content has loaded
13
+ page_source = driver.page_source
14
+
15
+ # Parse the HTML content
16
+ soup = BeautifulSoup(page_source, 'html.parser')
17
+
18
+ # Now you can use BeautifulSoup to extract information from the HTML
19
+ # For example, let's extract all image URLs
20
+ # print(soup.find_all('img'))
21
+
22
+ image_urls = [img['src'] for img in soup.find_all('img')]
23
+
24
+
25
+ # Print the extracted image URLs
26
+ for i, url in enumerate(image_urls, start=1):
27
+ print(f"Image {i}: {url}")
28
+ print(url.split('/asset/')[-1].split('/')[0])
29
+ break
30
+
31
+ # Close the browser window
32
+ driver.quit()
33
+
34
+
35
+
36
+ def get_image_asset(url):
37
+
38
+ return url.split('/asset/')[-1].split('/')[0]
species.json ADDED
The diff for this file is too large to render. See raw diff
 
test.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+
4
+ questions = [
5
+ {"image": "imgs/IMG_1.jpg", "options": ["a", "b", "c", "d"], "answer": "b"},
6
+ {"image": "imgs/IMG_2.jpg", "options": ["w", "x", "y", "z"], "answer": "y"},
7
+ ]
8
+
9
+
10
+ def check_question(option, ind):
11
+
12
+ print(option)
13
+ print(questions[ind]["answer"])
14
+
15
+ if option == questions[ind]["answer"]:
16
+ return "Correcto"
17
+ else:
18
+ return "Incorrecto"
19
+
20
+
21
+ ind = 0
22
+ with gr.Blocks() as demo:
23
+ # image = gr.Image(value="imgs/IMG_1.jpg", height=200, width=200)
24
+ # name = gr.Textbox(label="Name")
25
+ # output = gr.Textbox(label="Output Box")
26
+
27
+ image = gr.Image(value=questions[ind]["image"])
28
+ options = gr.Radio(choices=questions[ind]["options"])
29
+ button = gr.Button("Siguiente pregunta")
30
+ output = gr.Textbox(label="Output Box")
31
+
32
+
33
+ button.click(fn=check_question, inputs=[options, ind], outputs=output)
34
+ ind += 1
35
+
36
+ demo.launch()
test2.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ import json
4
+
5
+ with open('species.json') as f:
6
+ lista = json.load(f)
7
+
8
+
9
+
10
+ def inicializar_preguntas():
11
+ num_questions = 20
12
+
13
+ muestra_juego = random.sample(lista, num_questions)
14
+
15
+ questions = []
16
+
17
+ for especie in muestra_juego:
18
+ correcta = especie['name']
19
+ revision = True
20
+ while revision:
21
+ opciones = random.sample(lista, 3)
22
+ op_names = [op['name'] for op in opciones]
23
+ if not correcta in op_names:
24
+ op_names.append(correcta)
25
+ random.shuffle(op_names)
26
+ revision = False
27
+
28
+ # posicion_ultima_barra = especie['image_url'].rfind('/')
29
+ # enlace_recortado = especie['image_url'][:posicion_ultima_barra]
30
+ questions.append({"image": especie['image_url'], "options": op_names, "answer": correcta})
31
+ return questions
32
+
33
+ def check_question(option, ind, score, questions):
34
+ try:
35
+ questions = questions.value
36
+ except:
37
+ questions = questions
38
+
39
+ try:
40
+ score = score.value
41
+ except:
42
+ score = score
43
+
44
+ try:
45
+ ind = ind.value
46
+ except:
47
+ ind = ind
48
+
49
+
50
+
51
+ if ind == len(questions) - 1:
52
+ # # _, ind, score, image, options, _ = fin_preguntas()# restart_quiz()
53
+ # questions_list = inicializar_preguntas()
54
+ # questions = gr.State(questions_list)
55
+ # #ind = gr.State(0)
56
+ image = gr.Image(height=300, width=300)
57
+ options = gr.Radio() #choices=questions[ind.value]["options"])
58
+
59
+ if option == questions[ind]["answer"]:
60
+ score += 1
61
+ texto_corr = "Correcto"
62
+ else:
63
+ texto_corr = "Incorrecto\nLa respuesta correcta es: " + questions[ind]["answer"]
64
+
65
+ # try:
66
+ return texto_corr, ind, score, image, options, f"Terminó el quiz\nTuviste {score} de {ind} preguntas correctas\nScore: {int(score/len(questions)*100)}\nReinicie para empezar de nuevo"
67
+ # except:
68
+ # return texto_corr, ind, score, image, options, f"Terminó el quiz\nScore: {int(score.value/len(questions)*100)}\nReinicie para empezar de nuevo"
69
+
70
+
71
+
72
+ if option == questions[ind]["answer"]:
73
+ score += 1
74
+ texto_corr = "Correcto"
75
+ else:
76
+ texto_corr = "Incorrecto\nLa respuesta correcta es: " + questions[ind]["answer"]
77
+
78
+ ind += 1
79
+ image = gr.Image(value=questions[ind]["image"], height=300, width=300)
80
+ options = gr.Radio(choices=questions[ind]["options"])
81
+
82
+ return texto_corr, ind, score, image, options, f"Llevas: {score} de {ind} preguntas"
83
+
84
+ def restart_quiz():
85
+ score = gr.State(0)
86
+ questions_list = inicializar_preguntas()
87
+ questions = gr.State(questions_list)
88
+ try:
89
+ questions = questions.value
90
+ except:
91
+ questions = questions
92
+
93
+ try:
94
+ score = score.value
95
+ except:
96
+ score = score
97
+
98
+
99
+ # questions, ind, image, options = inicializar_preguntas()
100
+
101
+ ind = gr.State(0)
102
+ try:
103
+ ind = ind.value
104
+ except:
105
+ ind = ind
106
+
107
+ image = gr.Image(value=questions[ind]["image"], height=300, width=300)
108
+ options = gr.Radio(choices=questions[ind]["options"])
109
+
110
+ output = ""
111
+ return output, ind, score, image, options, f"", questions
112
+
113
+ def fin_preguntas():
114
+ # score = gr.State(0)
115
+ questions_list = inicializar_preguntas()
116
+ questions = gr.State(questions_list)
117
+ # questions, ind, image, options = inicializar_preguntas()
118
+
119
+ return "Fin", ind, score, image, options, f"Score: {int(score.value/len(questions)*100)}"
120
+
121
+
122
+ with gr.Blocks() as demo:
123
+ # Preguntas al azar
124
+ questions_list = inicializar_preguntas()
125
+ questions = gr.State(questions_list)
126
+ # Variables
127
+ score = gr.State(0)
128
+ ind = gr.State(0)
129
+ # Componentes
130
+ image = gr.Image(value=questions.value[ind.value]["image"], height=300, width=300)
131
+ options = gr.Radio(choices=questions.value[ind.value]["options"])
132
+ button = gr.Button("Siguiente pregunta")
133
+ output = gr.Textbox(label="Output Box")
134
+ output_score = gr.Textbox(label="Output Box")
135
+ restart_button = gr.Button("Restart")
136
+ # Funciones
137
+ button.click(fn=check_question, inputs=[options, ind, score, questions], outputs=[output, ind, score, image, options, output_score])
138
+ restart_button.click(fn=restart_quiz, inputs=[], outputs=[output, ind, score, image, options, output_score, questions])
139
+
140
+
141
+ if __name__ == "__main__":
142
+ demo.launch(share=True)
test_streamlit.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import random
3
+
4
+ # Display a title and instructions
5
+ st.title('Random Number Generator')
6
+ st.write('Click the button to generate a new random number.')
7
+
8
+ # When the button is clicked, Streamlit reruns the script from the top.
9
+ # Thus, we generate a new random number on each run.
10
+ if st.button('Refresh Number'):
11
+ random_number = random.randint(1, 100)
12
+ # Display the random number in the app.
13
+ st.write(f'Random Number: {random_number}')
14
+ else:
15
+ # Initial message before button is pressed for the first time.
16
+ st.write('Press the button to generate a random number.')