ludusc commited on
Commit
5b6e083
1 Parent(s): 52bd88d

updating wb to textiles

Browse files
Files changed (31) hide show
  1. data/CLIP_vecs_vases.pkl +0 -3
  2. data/annotated_files/seeds0000-100000.pkl +0 -3
  3. data/annotated_files/seeds0000-50000.pkl +0 -3
  4. data/annotated_files/sim_seeds0000-100000.csv +0 -3
  5. data/annotated_files/sim_seeds0000-50000.csv +0 -3
  6. data/model_files/network-snapshot-010600.pkl +0 -3
  7. data/old/ImageNet_metadata.csv +0 -3
  8. data/old/activation/convnext_activation.json +0 -3
  9. data/old/activation/mobilenet_activation.json +0 -3
  10. data/old/activation/resnet_activation.json +0 -3
  11. data/old/dot_architectures/convnext_architecture.dot +0 -3
  12. data/old/layer_infos/convnext_layer_infos.json +0 -3
  13. data/old/layer_infos/mobilenet_layer_infos.json +0 -3
  14. data/old/layer_infos/resnet_layer_infos.json +0 -3
  15. data/old/preprocessed_image_net/val_data_0.pkl +0 -3
  16. data/old/preprocessed_image_net/val_data_1.pkl +0 -3
  17. data/old/preprocessed_image_net/val_data_2.pkl +0 -3
  18. data/old/preprocessed_image_net/val_data_3.pkl +0 -3
  19. data/old/preprocessed_image_net/val_data_4.pkl +0 -3
  20. data/{CLIP_vecs.pkl → stored_vectors/scores_colors_hsv.csv} +2 -2
  21. data/vase_annotated_files/seeds0000-20000.pkl +0 -3
  22. data/vase_annotated_files/sim_Fabric_seeds0000-20000.csv +0 -3
  23. data/vase_annotated_files/sim_Provenance_seeds0000-20000.csv +0 -3
  24. data/vase_annotated_files/sim_Shape Name_seeds0000-20000.csv +0 -3
  25. data/vase_annotated_files/sim_Technique_seeds0000-20000.csv +0 -3
  26. data/vase_model_files/network-snapshot-003800.pkl +0 -3
  27. pages/1_Omniart_Disentanglement.py +0 -202
  28. pages/{5_Textiles_Disentanglement.py → 1_Textiles_Disentanglement.py} +4 -4
  29. pages/{2_Concepts_comparison.py → 2_Colours_comparison.py} +0 -0
  30. pages/3_Oxford_Vases_Disentanglement.py +0 -178
  31. pages/4_Vase_Qualities_Comparison copy.py +0 -268
data/CLIP_vecs_vases.pkl DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:c6299cd65f0635d6077788b135520ee8e88063930c63db458e643d77cba7b6ee
3
- size 995715
 
 
 
 
data/annotated_files/seeds0000-100000.pkl DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:7b3a4fd155fa86df0953ad1cb660d50729189606de307fcee09fd893ba047228
3
- size 420351795
 
 
 
 
data/annotated_files/seeds0000-50000.pkl DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:cd1bd97b8ff508b1d4a7ef43323530368ace65b35d12d84a914913f541187298
3
- size 314939226
 
 
 
 
data/annotated_files/sim_seeds0000-100000.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:6e0b08d729f87f827d3d88327b33ff22d8413cb7aa7057c0c4ccd384d72a2c21
3
- size 21090135
 
 
 
 
data/annotated_files/sim_seeds0000-50000.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:da82633e4296ae78ce9e3e208fae374ae8983137566101060aadd11ffd3b0ff7
3
- size 50535430
 
 
 
 
data/model_files/network-snapshot-010600.pkl DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:9a46e8aecd50191b82632b5de7bf3b9e219a59564c54994dd203f016b7a8270e
3
- size 357344749
 
 
 
 
data/old/ImageNet_metadata.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:e53b0fc17cd5c8811ca08b7ff908cd2bbd625147686ef8bc020cb85a5a4546e5
3
- size 3027633
 
 
 
 
data/old/activation/convnext_activation.json DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:0354b28bcca4e3673888124740e3d82882cbf38af8cd3007f48a7a5db983f487
3
- size 33350177
 
 
 
 
data/old/activation/mobilenet_activation.json DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:5abc76e9318fadee18f35bb54e90201bf28699cf75140b5d2482d42243fad302
3
- size 13564581
 
 
 
 
data/old/activation/resnet_activation.json DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:668bea355a5504d74f79d20d02954040ad572f50455361d7d17125c7c8b1561c
3
- size 23362905
 
 
 
 
data/old/dot_architectures/convnext_architecture.dot DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:41a258a40a93615638ae504770c14e44836c934badbe48f18148f5a750514ac9
3
- size 9108
 
 
 
 
data/old/layer_infos/convnext_layer_infos.json DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:3e82ea48865493107b97f37da58e370f0eead5677bf10f25f237f10970aedb6f
3
- size 1678
 
 
 
 
data/old/layer_infos/mobilenet_layer_infos.json DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:a11df5f0b23040d11ce817658a989c8faf19faa06a8cbad727b635bac824e917
3
- size 3578
 
 
 
 
data/old/layer_infos/resnet_layer_infos.json DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:21e1787382f1e1c206b81d2c4fe207fb6d41f4cf186d5afc32fc056dd21e10d6
3
- size 5155
 
 
 
 
data/old/preprocessed_image_net/val_data_0.pkl DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:2698bdc240555e2a46a40936df87275bc5852142d30e921ae0dad9289b0f576f
3
- size 906108480
 
 
 
 
data/old/preprocessed_image_net/val_data_1.pkl DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:21780d77e212695dbee84d6d2ad17a5a520bc1634f68e1c8fd120f069ad76da1
3
- size 907109023
 
 
 
 
data/old/preprocessed_image_net/val_data_2.pkl DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:2cfc83b78420baa1b2c3a8da92e7fba1f33443d506f483ecff13cdba2035ab3c
3
- size 907435149
 
 
 
 
data/old/preprocessed_image_net/val_data_3.pkl DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:2f5e2c7cb4d6bae17fbd062a0b46f2cee457ad466b725f7bdf0f8426069cafee
3
- size 906089333
 
 
 
 
data/old/preprocessed_image_net/val_data_4.pkl DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:4ed53c87ec8b9945db31f910eb44b7e3092324643de25ea53a99fc29137df854
3
- size 905439763
 
 
 
 
data/{CLIP_vecs.pkl → stored_vectors/scores_colors_hsv.csv} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:e2971a01a74a391c752fff9ba91c2939ffc6b29165842a87b911e67d9658df53
3
- size 412234
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:93f5789a80465ca7b21713819bc444d72239fa1b7ae56adf69e3323e0f3bedd1
3
+ size 974247
data/vase_annotated_files/seeds0000-20000.pkl DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:e790910bf45c0d5a84e74c9011b88012f59d0fc27b19987c890b891c57ab739c
3
- size 125913423
 
 
 
 
data/vase_annotated_files/sim_Fabric_seeds0000-20000.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:20fa48320e20998aad5665610083843705608a5f06ff081e4395ee4b5ac9cba3
3
- size 9731011
 
 
 
 
data/vase_annotated_files/sim_Provenance_seeds0000-20000.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:a421ffd119eee312249c9fbd05ac65460849e71f538d05fad223cb55423f315f
3
- size 18066428
 
 
 
 
data/vase_annotated_files/sim_Shape Name_seeds0000-20000.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:e258361e0db7c208ae67654c08ed5b900df10980e82e84bcddd3de89428f679a
3
- size 30853761
 
 
 
 
data/vase_annotated_files/sim_Technique_seeds0000-20000.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:e3d3425e15d76d47a8829783cadbd7072698083df199617a8423d5ccb9d88714
3
- size 2484876
 
 
 
 
data/vase_model_files/network-snapshot-003800.pkl DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:42be0a24e7021dc66a9353c3a904494bb8e64b62e00e535ad3b03ad18238b0d2
3
- size 357349976
 
 
 
 
pages/1_Omniart_Disentanglement.py DELETED
@@ -1,202 +0,0 @@
1
- import streamlit as st
2
- import pickle
3
- import pandas as pd
4
- import numpy as np
5
- import random
6
- import torch
7
-
8
- from matplotlib.backends.backend_agg import RendererAgg
9
-
10
- from backend.disentangle_concepts import *
11
- import torch_utils
12
- import dnnlib
13
- import legacy
14
-
15
- _lock = RendererAgg.lock
16
-
17
-
18
- st.set_page_config(layout='wide')
19
- BACKGROUND_COLOR = '#bcd0e7'
20
- SECONDARY_COLOR = '#bce7db'
21
-
22
-
23
- st.title('Disentanglement studies')
24
- st.write('> **What concepts can be disentangled in the latent spae of a model?**')
25
- st.write("""Explanation on the functionalities to come.""")
26
-
27
- instruction_text = """Instruction to input:
28
- 1. Choosing concept:
29
- 2. Choosing image: Users can choose a specific image by entering **Image ID** and hit the _Choose the defined image_ button or can generate an image randomly by hitting the _Generate a random image_ button.
30
- 3. Choosing epsilon: **Epsilon** is the lambda amount of translation along the disentangled concept axis. A negative epsilon changes the image in the direction of the concept, a positive one pushes the image away from the concept.
31
- """
32
- st.write("To use the functionality below, users need to input the **concept** to disentangle, an **image** id and the **epsilon** of variation along the disentangled axis.")
33
- with st.expander("See more instruction", expanded=False):
34
- st.write(instruction_text)
35
-
36
-
37
- annotations_file = './data/annotated_files/seeds0000-50000.pkl'
38
- with open(annotations_file, 'rb') as f:
39
- annotations = pickle.load(f)
40
-
41
- ann_df = pd.read_csv('./data/annotated_files/sim_seeds0000-50000.csv')
42
- concepts = './data/concepts.txt'
43
-
44
- with open(concepts) as f:
45
- labels = [line.strip() for line in f.readlines()]
46
-
47
- if 'image_id' not in st.session_state:
48
- st.session_state.image_id = 0
49
- if 'projection' not in st.session_state:
50
- st.session_state.projection = False
51
- if 'concept_id' not in st.session_state:
52
- st.session_state.concept_id = 'Abstract'
53
- if 'space_id' not in st.session_state:
54
- st.session_state.space_id = 'Z'
55
-
56
- # def on_change_random_input():
57
- # st.session_state.image_id = st.session_state.image_id
58
-
59
- # ----------------------------- INPUT ----------------------------------
60
- st.header('Input')
61
- input_col_1, input_col_2, input_col_3 = st.columns(3)
62
- # --------------------------- INPUT column 1 ---------------------------
63
- with input_col_1:
64
- with st.form('text_form'):
65
-
66
- # image_id = st.number_input('Image ID: ', format='%d', step=1)
67
- st.write('**Choose a concept to disentangle**')
68
- # chosen_text_id_input = st.empty()
69
- # concept_id = chosen_text_id_input.text_input('Concept:', value=st.session_state.concept_id)
70
- concept_id = st.selectbox('Concept:', tuple(labels))
71
-
72
- st.write('**Choose a latent space to disentangle**')
73
- # chosen_text_id_input = st.empty()
74
- # concept_id = chosen_text_id_input.text_input('Concept:', value=st.session_state.concept_id)
75
- space_id = st.selectbox('Space:', tuple(['Z', 'W']))
76
-
77
- choose_text_button = st.form_submit_button('Choose the defined concept and space to disentangle')
78
- # random_text = st.form_submit_button('Select a random concept')
79
-
80
- # if random_text:
81
- # concept_id = random.choice(labels)
82
- # st.session_state.concept_id = concept_id
83
- # chosen_text_id_input.text_input('Concept:', value=st.session_state.concept_id)
84
-
85
- if choose_text_button:
86
- concept_id = str(concept_id)
87
- st.session_state.concept_id = concept_id
88
- space_id = str(space_id)
89
- st.session_state.space_id = space_id
90
- # st.write(image_id, st.session_state.image_id)
91
-
92
- # ---------------------------- SET UP OUTPUT ------------------------------
93
- epsilon_container = st.empty()
94
- st.header('Output')
95
- st.subheader('Concept vector')
96
-
97
- # perform attack container
98
- # header_col_1, header_col_2, header_col_3, header_col_4, header_col_5 = st.columns([1,1,1,1,1])
99
- # output_col_1, output_col_2, output_col_3, output_col_4, output_col_5 = st.columns([1,1,1,1,1])
100
- header_col_1, header_col_2 = st.columns([5,1])
101
- output_col_1, output_col_2 = st.columns([5,1])
102
-
103
- st.subheader('Derivations along the concept vector')
104
-
105
- # prediction error container
106
- error_container = st.empty()
107
- smoothgrad_header_container = st.empty()
108
-
109
- # smoothgrad container
110
- smooth_head_1, smooth_head_2, smooth_head_3, smooth_head_4, smooth_head_5 = st.columns([1,1,1,1,1])
111
- smoothgrad_col_1, smoothgrad_col_2, smoothgrad_col_3, smoothgrad_col_4, smoothgrad_col_5 = st.columns([1,1,1,1,1])
112
-
113
- # ---------------------------- DISPLAY COL 1 ROW 1 ------------------------------
114
- with output_col_1:
115
- separation_vector, number_important_features, imp_nodes, performance = get_separation_space(concept_id, annotations, ann_df, latent_space=st.session_state.space_id)
116
- # st.write(f'Class ID {input_id} - {input_label}: {pred_prob*100:.3f}% confidence')
117
- st.write('Concept vector', separation_vector)
118
- header_col_1.write(f'Concept {concept_id} - Space {st.session_state.space_id} - Number of relevant nodes: {number_important_features} - Val classification performance: {performance}')# - Nodes {",".join(list(imp_nodes))}')
119
-
120
- # ----------------------------- INPUT column 2 & 3 ----------------------------
121
- with input_col_2:
122
- with st.form('image_form'):
123
-
124
- # image_id = st.number_input('Image ID: ', format='%d', step=1)
125
- st.write('**Choose or generate a random image to test the disentanglement**')
126
- chosen_image_id_input = st.empty()
127
- image_id = chosen_image_id_input.number_input('Image ID:', format='%d', step=1, value=st.session_state.image_id)
128
-
129
- choose_image_button = st.form_submit_button('Choose the defined image')
130
- random_id = st.form_submit_button('Generate a random image')
131
- projection_id = st.form_submit_button('Generate an image on the boudary')
132
-
133
- if random_id or projection_id:
134
- image_id = random.randint(0, 50000)
135
- st.session_state.image_id = image_id
136
- chosen_image_id_input.number_input('Image ID:', format='%d', step=1, value=st.session_state.image_id)
137
- st.session_state.projection = False
138
-
139
- if projection_id:
140
- st.session_state.projection = True
141
-
142
- if choose_image_button:
143
- image_id = int(image_id)
144
- st.session_state.image_id = int(image_id)
145
- # st.write(image_id, st.session_state.image_id)
146
-
147
- with input_col_3:
148
- with st.form('Variate along the disentangled concept'):
149
- st.write('**Set range of change**')
150
- chosen_epsilon_input = st.empty()
151
- epsilon = chosen_epsilon_input.number_input('Lambda:', min_value=1, step=1)
152
- epsilon_button = st.form_submit_button('Choose the defined lambda')
153
- st.write('**Select hierarchical levels to manipulate**')
154
- layers = st.multiselect('Layers:', tuple(range(14)))
155
- if len(layers) == 0:
156
- layers = None
157
- print(layers)
158
- layers_button = st.form_submit_button('Choose the defined layers')
159
-
160
-
161
- # ---------------------------- DISPLAY COL 2 ROW 1 ------------------------------
162
-
163
- #model = torch.load('./data/model_files/pytorch_model.bin', map_location=torch.device('cpu'))
164
- with dnnlib.util.open_url('./data/model_files/network-snapshot-010600.pkl') as f:
165
- model = legacy.load_network_pkl(f)['G_ema'].to('cpu') # type: ignore
166
-
167
- if st.session_state.space_id == 'Z':
168
- original_image_vec = annotations['z_vectors'][st.session_state.image_id]
169
- else:
170
- original_image_vec = annotations['w_vectors'][st.session_state.image_id]
171
-
172
- if st.session_state.projection:
173
- original_image_vec = original_image_vec - np.dot(original_image_vec, separation_vector.T) * separation_vector
174
- print(original_image_vec.shape)
175
-
176
- img = generate_original_image(original_image_vec, model, latent_space=st.session_state.space_id)
177
- # input_image = original_image_dict['image']
178
- # input_label = original_image_dict['label']
179
- # input_id = original_image_dict['id']
180
-
181
- with smoothgrad_col_3:
182
- st.image(img)
183
- smooth_head_3.write(f'Base image')
184
-
185
-
186
- images, lambdas = regenerate_images(model, original_image_vec, separation_vector, min_epsilon=-(int(epsilon)), max_epsilon=int(epsilon), latent_space=st.session_state.space_id, layers=layers)
187
-
188
- with smoothgrad_col_1:
189
- st.image(images[0])
190
- smooth_head_1.write(f'Change of {np.round(lambdas[0], 2)}')
191
-
192
- with smoothgrad_col_2:
193
- st.image(images[1])
194
- smooth_head_2.write(f'Change of {np.round(lambdas[1], 2)}')
195
-
196
- with smoothgrad_col_4:
197
- st.image(images[3])
198
- smooth_head_4.write(f'Change of {np.round(lambdas[3], 2)}')
199
-
200
- with smoothgrad_col_5:
201
- st.image(images[4])
202
- smooth_head_5.write(f'Change of {np.round(lambdas[4], 2)}')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
pages/{5_Textiles_Disentanglement.py → 1_Textiles_Disentanglement.py} RENAMED
@@ -23,18 +23,18 @@ SECONDARY_COLOR = '#bce7db'
23
  st.title('Disentanglement studies on the Textile Dataset')
24
  st.markdown(
25
  """
26
- This is a demo of the Disentanglement studies on the [Oxford Vases Dataset](https://www.robots.ox.ac.uk/~vgg/data/oxbuildings/).
27
  """,
28
  unsafe_allow_html=False,)
29
 
30
- annotations_file = './data/vase_annotated_files/seeds0000-20000.pkl'
31
  with open(annotations_file, 'rb') as f:
32
  annotations = pickle.load(f)
33
 
34
-
35
  if 'image_id' not in st.session_state:
36
  st.session_state.image_id = 0
37
- if 'concept_ids' not in st.session_state:
38
  st.session_state.concept_ids =['AMPHORA']
39
  if 'space_id' not in st.session_state:
40
  st.session_state.space_id = 'W'
 
23
  st.title('Disentanglement studies on the Textile Dataset')
24
  st.markdown(
25
  """
26
+ This is a demo of the Disentanglement studies on the [iMET Textiles Dataset](https://www.metmuseum.org/art/collection/search/85531).
27
  """,
28
  unsafe_allow_html=False,)
29
 
30
+ annotations_file = './data/textile_annotated_files/seeds0000-100000_S.pkl'
31
  with open(annotations_file, 'rb') as f:
32
  annotations = pickle.load(f)
33
 
34
+ COLORS_LIST = []
35
  if 'image_id' not in st.session_state:
36
  st.session_state.image_id = 0
37
+ if 'color_ids' not in st.session_state:
38
  st.session_state.concept_ids =['AMPHORA']
39
  if 'space_id' not in st.session_state:
40
  st.session_state.space_id = 'W'
pages/{2_Concepts_comparison.py → 2_Colours_comparison.py} RENAMED
File without changes
pages/3_Oxford_Vases_Disentanglement.py DELETED
@@ -1,178 +0,0 @@
1
- import streamlit as st
2
- import pickle
3
- import pandas as pd
4
- import numpy as np
5
- import random
6
- import torch
7
-
8
- from matplotlib.backends.backend_agg import RendererAgg
9
-
10
- from backend.disentangle_concepts import *
11
- import torch_utils
12
- import dnnlib
13
- import legacy
14
-
15
- _lock = RendererAgg.lock
16
-
17
-
18
- st.set_page_config(layout='wide')
19
- BACKGROUND_COLOR = '#bcd0e7'
20
- SECONDARY_COLOR = '#bce7db'
21
-
22
-
23
- st.title('Disentanglement studies on the Oxford Vases Dataset')
24
- st.markdown(
25
- """
26
- This is a demo of the Disentanglement studies on the [Oxford Vases Dataset](https://www.robots.ox.ac.uk/~vgg/data/oxbuildings/).
27
- """,
28
- unsafe_allow_html=False,)
29
-
30
- annotations_file = './data/vase_annotated_files/seeds0000-20000.pkl'
31
- with open(annotations_file, 'rb') as f:
32
- annotations = pickle.load(f)
33
-
34
-
35
- if 'image_id' not in st.session_state:
36
- st.session_state.image_id = 0
37
- if 'concept_ids' not in st.session_state:
38
- st.session_state.concept_ids =['AMPHORA']
39
- if 'space_id' not in st.session_state:
40
- st.session_state.space_id = 'W'
41
-
42
- # def on_change_random_input():
43
- # st.session_state.image_id = st.session_state.image_id
44
-
45
- # ----------------------------- INPUT ----------------------------------
46
- st.header('Input')
47
- input_col_1, input_col_2, input_col_3 = st.columns(3)
48
- # --------------------------- INPUT column 1 ---------------------------
49
- with input_col_1:
50
- with st.form('text_form'):
51
-
52
- # image_id = st.number_input('Image ID: ', format='%d', step=1)
53
- st.write('**Choose two options to disentangle**')
54
- type_col = st.selectbox('Concept category:', tuple(['Provenance', 'Shape Name', 'Fabric', 'Technique']))
55
-
56
- ann_df = pd.read_csv(f'./data/vase_annotated_files/sim_{type_col}_seeds0000-20000.csv')
57
- labels = list(ann_df.columns)
58
- labels.remove('ID')
59
- labels.remove('Unnamed: 0')
60
-
61
- concept_ids = st.multiselect('Concepts:', tuple(labels), max_selections=2, default=[labels[2], labels[3]])
62
-
63
- st.write('**Choose a latent space to disentangle**')
64
- space_id = st.selectbox('Space:', tuple(['W', 'Z']))
65
-
66
- choose_text_button = st.form_submit_button('Choose the defined concept and space to disentangle')
67
-
68
- if choose_text_button:
69
- concept_ids = list(concept_ids)
70
- st.session_state.concept_ids = concept_ids
71
- space_id = str(space_id)
72
- st.session_state.space_id = space_id
73
- # st.write(image_id, st.session_state.image_id)
74
-
75
- # ---------------------------- SET UP OUTPUT ------------------------------
76
- epsilon_container = st.empty()
77
- st.header('Output')
78
- st.subheader('Concept vector')
79
-
80
- # perform attack container
81
- # header_col_1, header_col_2, header_col_3, header_col_4, header_col_5 = st.columns([1,1,1,1,1])
82
- # output_col_1, output_col_2, output_col_3, output_col_4, output_col_5 = st.columns([1,1,1,1,1])
83
- header_col_1, header_col_2 = st.columns([5,1])
84
- output_col_1, output_col_2 = st.columns([5,1])
85
-
86
- st.subheader('Derivations along the concept vector')
87
-
88
- # prediction error container
89
- error_container = st.empty()
90
- smoothgrad_header_container = st.empty()
91
-
92
- # smoothgrad container
93
- smooth_head_1, smooth_head_2, smooth_head_3, smooth_head_4, smooth_head_5 = st.columns([1,1,1,1,1])
94
- smoothgrad_col_1, smoothgrad_col_2, smoothgrad_col_3, smoothgrad_col_4, smoothgrad_col_5 = st.columns([1,1,1,1,1])
95
-
96
- # ---------------------------- DISPLAY COL 1 ROW 1 ------------------------------
97
- with output_col_1:
98
- separation_vector, number_important_features, imp_nodes, performance = get_separation_space(concept_ids, annotations, ann_df, latent_space=st.session_state.space_id, samples=150)
99
- # st.write(f'Class ID {input_id} - {input_label}: {pred_prob*100:.3f}% confidence')
100
- st.write('Concept vector', separation_vector)
101
- header_col_1.write(f'Concept {st.session_state.concept_ids} - Space {st.session_state.space_id} - Number of relevant nodes: {number_important_features} - Val classification performance: {performance}')# - Nodes {",".join(list(imp_nodes))}')
102
-
103
- # ----------------------------- INPUT column 2 & 3 ----------------------------
104
- with input_col_2:
105
- with st.form('image_form'):
106
-
107
- # image_id = st.number_input('Image ID: ', format='%d', step=1)
108
- st.write('**Choose or generate a random image to test the disentanglement**')
109
- chosen_image_id_input = st.empty()
110
- image_id = chosen_image_id_input.number_input('Image ID:', format='%d', step=1, value=st.session_state.image_id)
111
-
112
- choose_image_button = st.form_submit_button('Choose the defined image')
113
- random_id = st.form_submit_button('Generate a random image')
114
-
115
- if random_id:
116
- image_id = random.randint(0, 20000)
117
- st.session_state.image_id = image_id
118
- chosen_image_id_input.number_input('Image ID:', format='%d', step=1, value=st.session_state.image_id)
119
-
120
- if choose_image_button:
121
- image_id = int(image_id)
122
- st.session_state.image_id = int(image_id)
123
- # st.write(image_id, st.session_state.image_id)
124
-
125
- with input_col_3:
126
- with st.form('Variate along the disentangled concept'):
127
- st.write('**Set range of change**')
128
- chosen_epsilon_input = st.empty()
129
- epsilon = chosen_epsilon_input.number_input('Lambda:', min_value=1, step=1)
130
- epsilon_button = st.form_submit_button('Choose the defined lambda')
131
- st.write('**Select hierarchical levels to manipulate**')
132
- layers = st.multiselect('Layers:', tuple(range(14)))
133
- if len(layers) == 0:
134
- layers = None
135
- print(layers)
136
- layers_button = st.form_submit_button('Choose the defined layers')
137
-
138
-
139
- # ---------------------------- DISPLAY COL 2 ROW 1 ------------------------------
140
-
141
- #model = torch.load('./data/model_files/pytorch_model.bin', map_location=torch.device('cpu'))
142
- with dnnlib.util.open_url('./data/vase_model_files/network-snapshot-003800.pkl') as f:
143
- model = legacy.load_network_pkl(f)['G_ema'].to('cpu') # type: ignore
144
-
145
- if st.session_state.space_id == 'Z':
146
- original_image_vec = annotations['z_vectors'][st.session_state.image_id]
147
- else:
148
- original_image_vec = annotations['w_vectors'][st.session_state.image_id]
149
-
150
- img = generate_original_image(original_image_vec, model, latent_space=st.session_state.space_id)
151
-
152
- top_pred = ann_df.loc[st.session_state.image_id, labels].astype(float).idxmax()
153
- # input_image = original_image_dict['image']
154
- # input_label = original_image_dict['label']
155
- # input_id = original_image_dict['id']
156
-
157
- with smoothgrad_col_3:
158
- st.image(img)
159
- smooth_head_3.write(f'Base image, predicted as {top_pred}')
160
-
161
-
162
- images, lambdas = regenerate_images(model, original_image_vec, separation_vector, min_epsilon=-(int(epsilon)), max_epsilon=int(epsilon), latent_space=st.session_state.space_id, layers=layers)
163
-
164
- with smoothgrad_col_1:
165
- st.image(images[0])
166
- smooth_head_1.write(f'Change of {np.round(lambdas[0], 2)}')
167
-
168
- with smoothgrad_col_2:
169
- st.image(images[1])
170
- smooth_head_2.write(f'Change of {np.round(lambdas[1], 2)}')
171
-
172
- with smoothgrad_col_4:
173
- st.image(images[3])
174
- smooth_head_4.write(f'Change of {np.round(lambdas[3], 2)}')
175
-
176
- with smoothgrad_col_5:
177
- st.image(images[4])
178
- smooth_head_5.write(f'Change of {np.round(lambdas[4], 2)}')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
pages/4_Vase_Qualities_Comparison copy.py DELETED
@@ -1,268 +0,0 @@
1
- import streamlit as st
2
- import streamlit.components.v1 as components
3
-
4
- import dnnlib
5
- import legacy
6
-
7
- import pickle
8
- import pandas as pd
9
- import numpy as np
10
- from pyvis.network import Network
11
-
12
- import random
13
- from sklearn.metrics.pairwise import cosine_similarity
14
-
15
- from matplotlib.backends.backend_agg import RendererAgg
16
-
17
- from backend.disentangle_concepts import *
18
-
19
- _lock = RendererAgg.lock
20
-
21
- HIGHTLIGHT_COLOR = '#e7bcc5'
22
- st.set_page_config(layout='wide')
23
-
24
-
25
- st.title('Comparison among concept vectors')
26
- st.write('> **How do the concept vectors relate to each other?**')
27
- st.write('> **What is their join impact on the image?**')
28
- st.write("""Description to write""")
29
-
30
-
31
- annotations_file = './data/vase_annotated_files/seeds0000-20000.pkl'
32
- with open(annotations_file, 'rb') as f:
33
- annotations = pickle.load(f)
34
-
35
- if 'image_id' not in st.session_state:
36
- st.session_state.image_id = 0
37
- if 'concept_ids' not in st.session_state:
38
- st.session_state.concept_ids = ['Provenance ADRIA']
39
- if 'space_id' not in st.session_state:
40
- st.session_state.space_id = 'Z'
41
- if 'type_col' not in st.session_state:
42
- st.session_state.type_col = 'Provenance'
43
-
44
- # def on_change_random_input():
45
- # st.session_state.image_id = st.session_state.image_id
46
-
47
- # ----------------------------- INPUT ----------------------------------
48
- st.header('Input')
49
- input_col_1, input_col_2, input_col_3 = st.columns(3)
50
- # --------------------------- INPUT column 1 ---------------------------
51
- with input_col_1:
52
- with st.form('text_form'):
53
-
54
- # image_id = st.number_input('Image ID: ', format='%d', step=1)
55
- st.write('**Choose two options to disentangle**')
56
- type_col = st.selectbox('Concept category:', tuple(['Provenance', 'Shape Name', 'Fabric', 'Technique']))
57
-
58
- ann_df = pd.read_csv(f'./data/vase_annotated_files/sim_{type_col}_seeds0000-20000.csv')
59
- labels = list(ann_df.columns)
60
- labels.remove('ID')
61
- labels.remove('Unnamed: 0')
62
-
63
- concept_ids = st.multiselect('Concepts:', tuple(labels), default=[labels[2], labels[3]])
64
-
65
- st.write('**Choose a latent space to disentangle**')
66
- # chosen_text_id_input = st.empty()
67
- # concept_id = chosen_text_id_input.text_input('Concept:', value=st.session_state.concept_id)
68
- space_id = st.selectbox('Space:', tuple(['Z', 'W']))
69
-
70
- choose_text_button = st.form_submit_button('Choose the defined concept and space to disentangle')
71
-
72
- if choose_text_button:
73
- st.session_state.concept_ids = list(concept_ids)
74
- space_id = str(space_id)
75
- st.session_state.space_id = space_id
76
- st.session_state.type_col = type_col
77
- # st.write(image_id, st.session_state.image_id)
78
-
79
- # ---------------------------- SET UP OUTPUT ------------------------------
80
- epsilon_container = st.empty()
81
- st.header('Output')
82
- st.subheader('Concept vector')
83
-
84
- # perform attack container
85
- # header_col_1, header_col_2, header_col_3, header_col_4, header_col_5 = st.columns([1,1,1,1,1])
86
- # output_col_1, output_col_2, output_col_3, output_col_4, output_col_5 = st.columns([1,1,1,1,1])
87
- header_col_1, header_col_2 = st.columns([1,1])
88
- output_col_1, output_col_2 = st.columns([1,1])
89
-
90
- st.subheader('Derivations along the concept vector')
91
-
92
- # prediction error container
93
- error_container = st.empty()
94
- smoothgrad_header_container = st.empty()
95
-
96
- # smoothgrad container
97
- smooth_head_1, smooth_head_2, smooth_head_3, smooth_head_4, smooth_head_5 = st.columns([1,1,1,1,1])
98
- smoothgrad_col_1, smoothgrad_col_2, smoothgrad_col_3, smoothgrad_col_4, smoothgrad_col_5 = st.columns([1,1,1,1,1])
99
-
100
- # ---------------------------- DISPLAY COL 1 ROW 1 ------------------------------
101
- with output_col_1:
102
- vectors, nodes_in_common, performances = get_concepts_vectors(concept_ids, annotations, ann_df, latent_space=space_id)
103
- header_col_1.write(f'Concepts {", ".join(concept_ids)} - Latent space {space_id} - Relevant nodes in common: {nodes_in_common} - Performance of the concept vectors: {performances}')# - Nodes {",".join(list(imp_nodes))}')
104
-
105
- edges = []
106
- for i in range(len(concept_ids)):
107
- for j in range(len(concept_ids)):
108
- if i != j:
109
- print(f'Similarity between {concept_ids[i]} and {concept_ids[j]}')
110
- similarity = cosine_similarity(vectors[i,:].reshape(1, -1), vectors[j,:].reshape(1, -1))
111
- print(np.round(similarity[0][0], 3))
112
- edges.append((concept_ids[i], concept_ids[j], np.round(similarity[0][0], 3)))
113
-
114
-
115
- net = Network(height="750px", width="100%",)
116
- for e in edges:
117
- src = e[0]
118
- dst = e[1]
119
- w = e[2]
120
-
121
- net.add_node(src, src, title=src)
122
- net.add_node(dst, dst, title=dst)
123
- net.add_edge(src, dst, value=w, title=src + ' to ' + dst + ' similarity ' +str(w))
124
-
125
- # Generate network with specific layout settings
126
- net.repulsion(
127
- node_distance=420,
128
- central_gravity=0.33,
129
- spring_length=110,
130
- spring_strength=0.10,
131
- damping=0.95
132
- )
133
-
134
- # Save and read graph as HTML file (on Streamlit Sharing)
135
- try:
136
- path = '/tmp'
137
- net.save_graph(f'{path}/pyvis_graph.html')
138
- HtmlFile = open(f'{path}/pyvis_graph.html', 'r', encoding='utf-8')
139
-
140
- # Save and read graph as HTML file (locally)
141
- except:
142
- path = '/html_files'
143
- net.save_graph(f'{path}/pyvis_graph.html')
144
- HtmlFile = open(f'{path}/pyvis_graph.html', 'r', encoding='utf-8')
145
-
146
- # Load HTML file in HTML component for display on Streamlit page
147
- components.html(HtmlFile.read(), height=435)
148
-
149
- with output_col_2:
150
- with open('data/CLIP_vecs_vases.pkl', 'rb') as f:
151
- vectors_CLIP = pickle.load(f)
152
-
153
- # st.write(f'Class ID {input_id} - {input_label}: {pred_prob*100:.3f}% confidence')
154
- #st.write('Concept vector', separation_vector)
155
- header_col_2.write(f'Concepts {", ".join(concept_ids)} - Latent space CLIP')# - Nodes {",".join(list(imp_nodes))}')
156
-
157
- edges_clip = []
158
- for c1 in concept_ids:
159
- for c2 in concept_ids:
160
- if c1 != c2:
161
-
162
- print(f'Similarity between {c1} and {c2}')
163
- similarity = cosine_similarity(vectors_CLIP[st.session_state.type_col + ' ' + c1].reshape(1, -1), vectors_CLIP[st.session_state.type_col + ' ' + c2].reshape(1, -1))
164
- print(np.round(similarity[0][0], 3))
165
- edges_clip.append((c1, c2, np.round(float(np.round(similarity[0][0], 3)), 3)))
166
-
167
-
168
- net_clip = Network(height="750px", width="100%",)
169
- for e in edges_clip:
170
- src = e[0]
171
- dst = e[1]
172
- w = e[2]
173
-
174
- net_clip.add_node(src, src, title=src)
175
- net_clip.add_node(dst, dst, title=dst)
176
- net_clip.add_edge(src, dst, value=w, title=src + ' to ' + dst + ' similarity ' +str(w))
177
-
178
- # Generate network with specific layout settings
179
- net_clip.repulsion(
180
- node_distance=420,
181
- central_gravity=0.33,
182
- spring_length=110,
183
- spring_strength=0.10,
184
- damping=0.95
185
- )
186
-
187
- # Save and read graph as HTML file (on Streamlit Sharing)
188
- try:
189
- path = '/tmp'
190
- net_clip.save_graph(f'{path}/pyvis_graph_clip.html')
191
- HtmlFile = open(f'{path}/pyvis_graph_clip.html', 'r', encoding='utf-8')
192
-
193
- # Save and read graph as HTML file (locally)
194
- except:
195
- path = '/html_files'
196
- net_clip.save_graph(f'{path}/pyvis_graph_clip.html')
197
- HtmlFile = open(f'{path}/pyvis_graph_clip.html', 'r', encoding='utf-8')
198
-
199
- # Load HTML file in HTML component for display on Streamlit page
200
- components.html(HtmlFile.read(), height=435)
201
-
202
- # ----------------------------- INPUT column 2 & 3 ----------------------------
203
- with input_col_2:
204
- with st.form('image_form'):
205
-
206
- # image_id = st.number_input('Image ID: ', format='%d', step=1)
207
- st.write('**Choose or generate a random image to test the disentanglement**')
208
- chosen_image_id_input = st.empty()
209
- image_id = chosen_image_id_input.number_input('Image ID:', format='%d', step=1, value=st.session_state.image_id)
210
-
211
- choose_image_button = st.form_submit_button('Choose the defined image')
212
- random_id = st.form_submit_button('Generate a random image')
213
-
214
- if random_id:
215
- image_id = random.randint(0, 50000)
216
- st.session_state.image_id = image_id
217
- chosen_image_id_input.number_input('Image ID:', format='%d', step=1, value=st.session_state.image_id)
218
-
219
- if choose_image_button:
220
- image_id = int(image_id)
221
- st.session_state.image_id = int(image_id)
222
- # st.write(image_id, st.session_state.image_id)
223
-
224
- with input_col_3:
225
- with st.form('Variate along the disentangled concepts'):
226
- st.write('**Set range of change**')
227
- chosen_epsilon_input = st.empty()
228
- epsilon = chosen_epsilon_input.number_input('Epsilon:', min_value=1, step=1)
229
- epsilon_button = st.form_submit_button('Choose the defined epsilon')
230
-
231
- # # ---------------------------- DISPLAY COL 2 ROW 1 ------------------------------
232
-
233
-
234
- with dnnlib.util.open_url('./data/vase_model_files/network-snapshot-003800.pkl') as f:
235
- model = legacy.load_network_pkl(f)['G_ema'].to('cpu') # type: ignore
236
-
237
- if st.session_state.space_id == 'Z':
238
- original_image_vec = annotations['z_vectors'][st.session_state.image_id]
239
- else:
240
- original_image_vec = annotations['w_vectors'][st.session_state.image_id]
241
-
242
- img = generate_original_image(original_image_vec, model, latent_space=st.session_state.space_id)
243
- # input_image = original_image_dict['image']
244
- # input_label = original_image_dict['label']
245
- # input_id = original_image_dict['id']
246
-
247
- with smoothgrad_col_3:
248
- st.image(img)
249
- smooth_head_3.write(f'Base image')
250
-
251
-
252
- images, lambdas = generate_joint_effect(model, original_image_vec, vectors, min_epsilon=-(int(epsilon)), max_epsilon=int(epsilon), latent_space=st.session_state.space_id)
253
-
254
- with smoothgrad_col_1:
255
- st.image(images[0])
256
- smooth_head_1.write(f'Change of {np.round(lambdas[0], 2)}')
257
-
258
- with smoothgrad_col_2:
259
- st.image(images[1])
260
- smooth_head_2.write(f'Change of {np.round(lambdas[1], 2)}')
261
-
262
- with smoothgrad_col_4:
263
- st.image(images[3])
264
- smooth_head_4.write(f'Change of {np.round(lambdas[3], 2)}')
265
-
266
- with smoothgrad_col_5:
267
- st.image(images[4])
268
- smooth_head_5.write(f'Change of {np.round(lambdas[4], 2)}')