Dimitre commited on
Commit
be7716c
1 Parent(s): 6953711

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -0
app.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import random
3
+ import numpy as np
4
+ import streamlit as st
5
+ import tensorflow as tf
6
+ import matplotlib.pyplot as plt
7
+
8
+
9
+ @st.cache(allow_output_mutation=True)
10
+ def load_model():
11
+ generator = tf.keras.models.load_model("./models/")
12
+ return generator
13
+
14
+ def generate(n_images, generator, seed=42, codings_size=100):
15
+ noise = tf.random.normal(shape=[n_images, codings_size], seed=seed)
16
+ generated_images = generator(noise, training=False)
17
+ return generated_images.numpy()
18
+
19
+ def get_captcha(images, indexes):
20
+ fake_idx = []
21
+ fig, axis = plt.subplots(3, 3, figsize=(10, 10))
22
+ axis = axis.flatten()
23
+
24
+ for ax_idx, idx in enumerate(indexes):
25
+ if indexes[idx] < n_fake:
26
+ fake_idx.append(idx)
27
+ axis[ax_idx].imshow(images[idx])
28
+ axis[ax_idx].set_title(f"Punk {ax_idx+1}")
29
+ axis[ax_idx].axis('off')
30
+ return fig, fake_idx
31
+
32
+ def get_challenge():
33
+ real_idx = np.random.randint(low=0, high=len(real_files), size=n_real)
34
+ real_samples = np.array([plt.imread(real_files[idx]) for idx in real_idx])
35
+ generated_samples = generate(n_fake, generator)
36
+ captcha_samples = np.concatenate((generated_samples, real_samples))
37
+
38
+ captcha_idx = [x for x in range(len(captcha_samples))]
39
+ random.shuffle(captcha_idx)
40
+
41
+ fig, fake_idx = get_captcha(captcha_samples, captcha_idx)
42
+ correct_answer = [f"Punk {x+1}" for x in fake_idx]
43
+ correct_answer.sort()
44
+ st.session_state.session_captcha = fig
45
+ st.session_state.correct = correct_answer
46
+
47
+ # Session captcha
48
+ if 'session_captcha' not in st.session_state:
49
+ st.session_state['session_captcha'] = None
50
+ if 'correct' not in st.session_state:
51
+ st.session_state['correct'] = []
52
+
53
+ n_real = 6
54
+ n_fake = 3
55
+ n_samples = n_real + n_fake
56
+ real_images_path = "./data/images"
57
+ real_files = glob.glob(f"{real_images_path}/*")
58
+ generator = load_model()
59
+
60
+ st.title("CryptoPunk Captcha")
61
+ st.header("Are you a human?")
62
+ st.subheader("Choose the 3 fake CryptoPunks")
63
+
64
+ if st.session_state.session_captcha is None:
65
+ get_challenge()
66
+
67
+ st.pyplot(st.session_state.session_captcha) # Display captcha
68
+ options = st.multiselect('Choose',[f"Punk {x+1}" for x in range(n_samples)]) # Selected options
69
+ to_verify = st.button("Verify")
70
+
71
+ if to_verify:
72
+ options.sort()
73
+ verified = st.session_state.correct == options
74
+ if verified:
75
+ st.write("Correct")
76
+ else:
77
+ st.write("Wrong")
78
+ get_challenge() # Refresh challenge
79
+ st.button("Try again?")