JVice commited on
Commit
03b145d
1 Parent(s): a2f9330

Preparing for TBYB V2

Browse files
Files changed (1) hide show
  1. app.py +64 -178
app.py CHANGED
@@ -1,6 +1,5 @@
1
  import streamlit as st
2
- st.set_page_config(layout="centered")
3
- import streamlit_authenticator as stauth
4
  from uuid import uuid4
5
  import model_comparison as MCOMP
6
  import model_loading as MLOAD
@@ -17,114 +16,8 @@ from huggingface_hub import CommitScheduler, login, snapshot_download
17
  login(token=os.environ.get("HF_TOKEN"), write_permission=True)
18
 
19
 
20
- AUTHENTICATOR = None
21
  TBYB_LOGO = Image.open('./assets/TBYB_logo_light.png')
22
- USER_LOGGED_IN = False
23
 
24
-
25
- USER_DATABASE_DIR = Path("data")
26
- USER_DATABASE_DIR.mkdir(parents=True, exist_ok=True)
27
-
28
- USER_DATABASE_PATH = USER_DATABASE_DIR / f"user_database.yaml"
29
-
30
- USER_DATABASE_UPDATE_SCHEDULER = CommitScheduler(
31
- repo_id="try-before-you-bias-data",
32
- repo_type="dataset",
33
- folder_path=USER_DATABASE_DIR,
34
- path_in_repo="data",
35
- every=1,
36
- )
37
- def create_new_user(authenticator, users):
38
-
39
- try:
40
- if authenticator.register_user('Register user', preauthorization=False):
41
- st.success('User registered successfully')
42
- except Exception as e:
43
- st.error(e)
44
- with USER_DATABASE_UPDATE_SCHEDULER.lock:
45
- with USER_DATABASE_PATH.open('w') as file:
46
- yaml.dump(users, file, default_flow_style=False)
47
-
48
-
49
- def forgot_password(authenticator, users):
50
- try:
51
- username_of_forgotten_password, email_of_forgotten_password, new_random_password = authenticator.forgot_password(
52
- 'Forgot password')
53
- if username_of_forgotten_password:
54
- st.success('New password to be sent securely')
55
- # Random password should be transferred to user securely
56
- except Exception as e:
57
- st.error(e)
58
- with USER_DATABASE_UPDATE_SCHEDULER.lock:
59
- with open(USER_DATABASE_PATH, 'w') as file:
60
- yaml.dump(users, file, default_flow_style=False)
61
- def update_account_details(authenticator, users):
62
- if st.session_state["authentication_status"]:
63
- try:
64
- if authenticator.update_user_details(st.session_state["username"], 'Update user details'):
65
- st.success('Entries updated successfully')
66
- except Exception as e:
67
- st.error(e)
68
- with USER_DATABASE_UPDATE_SCHEDULER.lock:
69
- with open(USER_DATABASE_PATH, 'w') as file:
70
- yaml.dump(users, file, default_flow_style=False)
71
- def reset_password(authenticator, users):
72
- if st.session_state["authentication_status"]:
73
- try:
74
- if authenticator.reset_password(st.session_state["username"], 'Reset password'):
75
- st.success('Password modified successfully')
76
- except Exception as e:
77
- st.error(e)
78
- with USER_DATABASE_UPDATE_SCHEDULER.lock:
79
- with open(USER_DATABASE_PATH, 'w') as file:
80
- yaml.dump(users, file, default_flow_style=False)
81
- def user_login_create():
82
- global AUTHENTICATOR
83
- global TBYB_LOGO
84
- global USER_LOGGED_IN
85
- users = None
86
- snapshot_download(repo_id='JVice/try-before-you-bias-data',repo_type='dataset',local_dir='user_data')
87
- with open('user_data/data/user_database.yaml') as file:
88
- users = yaml.load(file, Loader=SafeLoader)
89
- AUTHENTICATOR = stauth.Authenticate(
90
- users['credentials'],
91
- users['cookie']['name'],
92
- users['cookie']['key'],
93
- users['cookie']['expiry_days'],
94
- users['preauthorized']
95
- )
96
-
97
- with st.sidebar:
98
- st.image(TBYB_LOGO, width=70)
99
- loginTab, registerTab, detailsTab = st.tabs(["Log in", "Register", "Account details"])
100
-
101
- with loginTab:
102
- # name, authentication_status, username = AUTHENTICATOR.login('Login', 'main')
103
- name, authentication_status, username = AUTHENTICATOR.login('main', fields = {'Form name': 'Login'})
104
- if authentication_status:
105
- AUTHENTICATOR.logout('Logout', 'main')
106
- st.write(f'Welcome *{name}*')
107
- user_evaluation_variables.USERNAME = username
108
- USER_LOGGED_IN = True
109
- elif authentication_status == False:
110
- st.error('Username/password is incorrect')
111
- forgot_password(AUTHENTICATOR, users)
112
- elif authentication_status == None:
113
- st.warning('Please enter your username and password')
114
- forgot_password(AUTHENTICATOR, users)
115
- if not authentication_status:
116
- with registerTab:
117
- create_new_user(AUTHENTICATOR, users)
118
- else:
119
- with detailsTab:
120
- st.write('**Username:** ', username)
121
- st.write('**Name:** ', name)
122
- st.write('**Email:** ', users['credentials']['usernames'][username]['email'])
123
- # update_account_details(AUTHENTICATOR, users)
124
- reset_password(AUTHENTICATOR, users)
125
-
126
-
127
- return USER_LOGGED_IN
128
  def setup_page_banner():
129
  global USER_LOGGED_IN
130
  # for tab in [tab1, tab2, tab3, tab4, tab5]:
@@ -138,18 +31,17 @@ def setup_page_banner():
138
  def setup_how_to():
139
  expander = st.expander("How to Use")
140
  expander.write("1. Watch our tutorial video series on [YouTube](https://www.youtube.com/channel/UCk-0xyUyT0MSd_hkp4jQt1Q)\n"
141
- "2. Login to your TBYB Account using the bar on the left\n"
142
- "3. Navigate to the '\U0001F527 Setup' tab and input the ID of the HuggingFace \U0001F917 T2I model you want to evaluate\n")
143
  expander.image(Image.open('./assets/HF_MODEL_ID_EXAMPLE.png'))
144
- expander.write("4. Test your chosen model by generating an image using an input prompt e.g.: 'A corgi with some cool sunglasses'\n")
145
  expander.image(Image.open('./assets/lykon_corgi.png'))
146
- expander.write("5. Navigate to the '\U0001F30E Bias Evaluation (BEval)' or '\U0001F3AF Task-Oriented BEval' tabs "
147
  " to evaluate your model once it has been loaded\n"
148
- "6. Once you have generated some evaluation images, head over to the '\U0001F4C1 Generated Images' tab to have a look at them\n"
149
- "7. To check out your evaluations or all of the TBYB Community evaluations, head over to the '\U0001F4CA Model Comparison' tab\n"
150
- "8. For more information about the evaluation process, see our paper on [ArXiv](https://arxiv.org/abs/2312.13053) or navigate to the "
151
  " '\U0001F4F0 Additional Information' tab for a TL;DR.\n"
152
- "9. For any questions or to report any bugs/issues. Please contact [email protected].\n")
153
 
154
  def setup_additional_information_tab(tab):
155
  with tab:
@@ -276,12 +168,13 @@ def setup_additional_information_tab(tab):
276
  - Currently, a model_index.json file is required to load models and use them with TBYB, we will look to
277
  address other models in the future.
278
  - Target models must be public. Gated models are currently not supported.
279
- - Images are generated using square resolutions based on user inputs. Width and height modifiers will be added soon.
280
- - TBYB only works on T2I models hosted on HuggingFace, other model repositories are not currently supported
281
  - Adaptor models are currently not supported, we will look to add evaluation functionalities of these
282
  models in the future.
283
- - Download, generation, inference and evaluation times are hardware dependent. We are currently deploying the
284
- TBYB space on a T4 GPU. With more funding and interest (usage), we plan on deploying more powerful GPU options.
 
 
285
 
286
  Keep in mind that these constraints may be removed or added to any time.
287
  """)
@@ -311,66 +204,59 @@ setup_page_banner()
311
  setup_how_to()
312
 
313
 
314
- if user_login_create():
315
- tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs(["\U0001F527 Setup", "\U0001F30E Bias Evaluation (BEval)", "\U0001F3AF Task-Oriented BEval.",
316
- "\U0001F4CA Model Comparison", "\U0001F4C1 Generated Images", "\U0001F4F0 Additional Information"])
317
- setup_additional_information_tab(tab6)
318
 
319
- # PLASTER THE LOGO EVERYWHERE
320
- tab2.subheader("General Bias Evaluation")
321
- tab2.write("Waiting for \U0001F527 Setup to be complete...")
322
- tab3.subheader("Task-Oriented Bias Evaluation")
323
- tab3.write("Waiting for \U0001F527 Setup to be complete...")
324
- tab4.write("Check out other model evaluation results from users across the **TBYB** Community! \U0001F30E ")
325
- tab4.write("You can also just compare your own model evaluations by clicking the '*Personal Evaluation*' buttons")
326
- MCOMP.initialise_page(tab4)
327
- tab5.subheader("Generated Images from General and Task-Oriented Bias Evaluations")
328
- tab5.write("Waiting for \U0001F527 Setup to be complete...")
329
 
330
- with tab1:
331
- with st.form("model_definition_form", clear_on_submit=True):
332
- modelID = st.text_input('Input the HuggingFace \U0001F917 T2I model_id for the model you '
333
- 'want to analyse e.g.: "runwayml/stable-diffusion-v1-5"')
334
- submitted1 = st.form_submit_button("Submit")
335
- if modelID:
336
- with st.spinner('Checking if ' + modelID + ' is valid and downloading it (if required)'):
337
- modelLoaded = MLOAD.check_if_model_exists(modelID)
338
- if modelLoaded is not None:
339
- # st.write("Located " + modelID + " model_index.json file")
340
- st.write("Located " + modelID)
341
 
342
- modelType = MLOAD.get_model_info(modelLoaded)
343
- if modelType is not None:
344
- st.write("Model is of Type: ", modelType)
345
 
346
- if submitted1:
347
- MINFER.TargetModel = MLOAD.import_model(modelID, modelType)
348
- if MINFER.TargetModel is not None:
349
- st.write("Text-to-image pipeline looks like this:")
350
- st.write(MINFER.TargetModel)
351
- user_evaluation_variables.MODEL = modelID
352
- user_evaluation_variables.MODEL_TYPE = modelType
353
- else:
354
- st.error('The Model: ' + modelID + ' does not appear to exist or the model does not contain a model_index.json file.'
355
- ' Please check that that HuggingFace repo ID is valid.'
356
- ' For more help, please see the "How to Use" Tab above.', icon="🚨")
357
- if modelID:
358
- with st.form("example_image_gen_form", clear_on_submit=True):
359
- testPrompt = st.text_input('Input a random test prompt to test out your '
360
- 'chosen model and see if its generating images:')
361
- submitted2 = st.form_submit_button("Submit")
362
- if testPrompt and submitted2:
363
- with st.spinner("Generating an image with the prompt:\n"+testPrompt+"(This may take some time)"):
364
- testImage = MINFER.generate_test_image(MINFER.TargetModel, testPrompt)
365
- st.image(testImage, caption='Model: ' + modelID + ' Prompt: ' + testPrompt)
366
- st.write('''If you are happy with this model, navigate to the other tabs to evaluate bias!
367
- Otherwise, feel free to load up a different model and run it again''')
368
 
369
- if MINFER.TargetModel is not None:
370
- tab_manager.completed_setup([tab2, tab3, tab4, tab5], modelID)
371
- else:
372
- MCOMP.databaseDF = None
373
- user_evaluation_variables.reset_variables('general')
374
- user_evaluation_variables.reset_variables('task-oriented')
375
- st.write('')
376
- st.warning('Log in or register your email to get started! ', icon="⚠️")
 
1
  import streamlit as st
2
+ st.set_page_config(layout="wide")
 
3
  from uuid import uuid4
4
  import model_comparison as MCOMP
5
  import model_loading as MLOAD
 
16
  login(token=os.environ.get("HF_TOKEN"), write_permission=True)
17
 
18
 
 
19
  TBYB_LOGO = Image.open('./assets/TBYB_logo_light.png')
 
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  def setup_page_banner():
22
  global USER_LOGGED_IN
23
  # for tab in [tab1, tab2, tab3, tab4, tab5]:
 
31
  def setup_how_to():
32
  expander = st.expander("How to Use")
33
  expander.write("1. Watch our tutorial video series on [YouTube](https://www.youtube.com/channel/UCk-0xyUyT0MSd_hkp4jQt1Q)\n"
34
+ "2. Navigate to the '\U0001F527 Setup' tab and input the ID of the HuggingFace \U0001F917 T2I model you want to evaluate\n")
 
35
  expander.image(Image.open('./assets/HF_MODEL_ID_EXAMPLE.png'))
36
+ expander.write("3. Test your chosen model by generating an image using an input prompt e.g.: 'A corgi with some cool sunglasses'\n")
37
  expander.image(Image.open('./assets/lykon_corgi.png'))
38
+ expander.write("4. Navigate to the '\U0001F30E Bias Evaluation (BEval)' or '\U0001F3AF Task-Oriented BEval' tabs "
39
  " to evaluate your model once it has been loaded\n"
40
+ "5. Once you have generated some evaluation images, head over to the '\U0001F4C1 Generated Images' tab to have a look at them\n"
41
+ "6. To check out your evaluations or all of the TBYB Community evaluations, head over to the '\U0001F4CA Model Comparison' tab\n"
42
+ "7. For more information about the evaluation process, see our paper on [ArXiv](https://arxiv.org/abs/2312.13053) or navigate to the "
43
  " '\U0001F4F0 Additional Information' tab for a TL;DR.\n"
44
+ "8. For any questions or to report any bugs/issues. Please contact [email protected].\n")
45
 
46
  def setup_additional_information_tab(tab):
47
  with tab:
 
168
  - Currently, a model_index.json file is required to load models and use them with TBYB, we will look to
169
  address other models in the future.
170
  - Target models must be public. Gated models are currently not supported.
171
+ - TBYB only works on T2I models hosted on HuggingFace, other model repositories are not currently supported.
 
172
  - Adaptor models are currently not supported, we will look to add evaluation functionalities of these
173
  models in the future.
174
+ - Download, generation, inference and evaluation times are hardware and model dependent. We are currently deploying the
175
+ TBYB space on a T4 GPU. With more funding and interest (usage).
176
+ - BLIP and CLIP models used for evaluations are limited by their own biases and object recognition
177
+ capabilities. However, manual evaluations of bias could result in subjective labelling biases.
178
 
179
  Keep in mind that these constraints may be removed or added to any time.
180
  """)
 
204
  setup_how_to()
205
 
206
 
207
+ tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs(["\U0001F527 Setup", "\U0001F30E Bias Evaluation (BEval)", "\U0001F3AF Task-Oriented BEval.",
208
+ "\U0001F4CA Model Comparison", "\U0001F4C1 Generated Images", "\U0001F4F0 Additional Information"])
209
+ setup_additional_information_tab(tab6)
 
210
 
211
+ # PLASTER THE LOGO EVERYWHERE
212
+ tab2.subheader("General Bias Evaluation")
213
+ tab2.write("Waiting for \U0001F527 Setup to be complete...")
214
+ tab3.subheader("Task-Oriented Bias Evaluation")
215
+ tab3.write("Waiting for \U0001F527 Setup to be complete...")
216
+ tab4.write("Check out other model evaluation results from users across the **TBYB** Community! \U0001F30E ")
217
+ tab4.write("You can also just compare your own model evaluations by clicking the '*Personal Evaluation*' buttons")
218
+ MCOMP.initialise_page(tab4)
219
+ tab5.subheader("Generated Images from General and Task-Oriented Bias Evaluations")
220
+ tab5.write("Waiting for \U0001F527 Setup to be complete...")
221
 
222
+ with tab1:
223
+ with st.form("model_definition_form", clear_on_submit=True):
224
+ modelID = st.text_input('Input the HuggingFace \U0001F917 T2I model_id for the model you '
225
+ 'want to analyse e.g.: "runwayml/stable-diffusion-v1-5"')
226
+ submitted1 = st.form_submit_button("Submit")
227
+ if modelID:
228
+ with st.spinner('Checking if ' + modelID + ' is valid and downloading it (if required)'):
229
+ modelLoaded = MLOAD.check_if_model_exists(modelID)
230
+ if modelLoaded is not None:
231
+ # st.write("Located " + modelID + " model_index.json file")
232
+ st.write("Located " + modelID)
233
 
234
+ modelType = MLOAD.get_model_info(modelLoaded)
235
+ if modelType is not None:
236
+ st.write("Model is of Type: ", modelType)
237
 
238
+ if submitted1:
239
+ MINFER.TargetModel = MLOAD.import_model(modelID, modelType)
240
+ if MINFER.TargetModel is not None:
241
+ st.write("Text-to-image pipeline looks like this:")
242
+ st.write(MINFER.TargetModel)
243
+ user_evaluation_variables.MODEL = modelID
244
+ user_evaluation_variables.MODEL_TYPE = modelType
245
+ else:
246
+ st.error('The Model: ' + modelID + ' does not appear to exist or the model does not contain a model_index.json file.'
247
+ ' Please check that that HuggingFace repo ID is valid.'
248
+ ' For more help, please see the "How to Use" Tab above.', icon="🚨")
249
+ if modelID:
250
+ with st.form("example_image_gen_form", clear_on_submit=True):
251
+ testPrompt = st.text_input('Input a random test prompt to test out your '
252
+ 'chosen model and see if its generating images:')
253
+ submitted2 = st.form_submit_button("Submit")
254
+ if testPrompt and submitted2:
255
+ with st.spinner("Generating an image with the prompt:\n"+testPrompt+"(This may take some time)"):
256
+ testImage = MINFER.generate_test_image(MINFER.TargetModel, testPrompt)
257
+ st.image(testImage, caption='Model: ' + modelID + ' Prompt: ' + testPrompt)
258
+ st.write('''If you are happy with this model, navigate to the other tabs to evaluate bias!
259
+ Otherwise, feel free to load up a different model and run it again''')
260
 
261
+ if MINFER.TargetModel is not None:
262
+ tab_manager.completed_setup([tab2, tab3, tab4, tab5], modelID)