emvecchi commited on
Commit
461a1ac
·
verified ·
1 Parent(s): 106cc62

Delete app2.py

Browse files
Files changed (1) hide show
  1. app2.py +0 -620
app2.py DELETED
@@ -1,620 +0,0 @@
1
- import json
2
- import os
3
- from dataclasses import dataclass, field
4
- from typing import List, Optional, Dict
5
- from PIL import Image
6
-
7
- import numpy as np
8
- import pandas as pd
9
- import streamlit as st
10
- from fsspec.implementations.local import LocalFileSystem
11
- from huggingface_hub import HfFileSystem
12
-
13
- import streamlit.components.v1 as components
14
-
15
- @dataclass
16
- class Field:
17
- type: str
18
- title: str
19
- name: str = None
20
- mandatory: bool = True
21
- # if value of field is in the list of those values, makes following siblings mandatory
22
- following_mandatory_values: list = False
23
- skip_mandatory: bool = False
24
- help: Optional[str] = None
25
- children: Optional[List['Field']] = None
26
- other_params: Optional[Dict[str, object]] = field(default_factory=lambda: {})
27
-
28
- # Function to get user ID from URL
29
- def get_param_from_url(param):
30
- user_id = st.query_params.get(param, "")
31
- return user_id
32
-
33
-
34
- ########################################################################################
35
- # CHANGE THE FOLLOWING VARIABLES ACCORDING TO YOUR NEEDS
36
-
37
- # 'local' or 'hf'. hf is for Hugging Face file system but has limits on the number of access per hour
38
- filesystem = 'hf'
39
- # path to repo or local file system TODO rename
40
- input_repo_path = 'datasets/emvecchi/therapy_annotation'
41
- output_repo_path = 'datasets/emvecchi/therapy_annotation/pilot'
42
-
43
-
44
- #st.set_page_config(page_title="Therapy Session Annotation", layout="wide")
45
- st.set_page_config(layout='wide')
46
-
47
- to_annotate_file_name = 'to_annotate.csv' # CSV file to annotate
48
- COLS_TO_SAVE = ['dialogue_id','dialogue_name','generatedPatient']
49
-
50
- agreement_labels = ['strongly disagree', 'disagree', 'neither agree no disagree', 'agree', 'strongly agree']
51
- quality_labels = ['very poor', 'poor', 'acceptable', 'good', 'very good']
52
- priority_labels = ['not a priority', 'low priority', 'neutral', 'moderate priority', 'high priority']
53
- yes_no_labels = ['no','yes']
54
- yes_no_other_labels = ['no','yes','other']
55
- default_labels = agreement_labels
56
-
57
- function_choices = ['Broadening Discussion',
58
- 'Improving Comment Quality',
59
- 'Content Correction',
60
- 'Keeping Discussion on Topic',
61
- 'Organizing Discussion',
62
- 'Policing',
63
- 'Resolving Site Use Issues',
64
- 'Social Functions',
65
- 'Other (please specify)']
66
- property_choices = ['appropriateness',
67
- 'clarity',
68
- 'constructiveness',
69
- 'common good',
70
- 'effectiveness',
71
- 'emotion',
72
- 'impact',
73
- 'overall quality',
74
- 'proposal',
75
- 'Q for justification',
76
- 'storytelling',
77
- 'rationality',
78
- 'reasonableness',
79
- 'reciprocity',
80
- 'reference',
81
- 'respect',
82
- 'moderation behavior',
83
- 'Other (please specify)']
84
- assistance_choices = ['Expand the breadth of moderator role',
85
- 'Reduce my own bias',
86
- #'Assist with recall',
87
- 'Avoids me missing relevant instances',
88
- 'Improve speed of moderation tasks',
89
- 'Manage prioritization of comments to consider',
90
- 'Visualization of properties narrows down moderator contribution',
91
- 'Other (please specify)']
92
-
93
- default_choices = function_choices
94
-
95
- consent_text = '''
96
- ## Consent Form
97
-
98
- You will be asked to take part in a research study. Before you decide to take part in this study, it is important that you understand why the study is being done and what it involves. Please read the following information carefully.
99
- ________________________________________________________________________________________
100
-
101
- Project title: [...]\\
102
- Researchers: [...]\\
103
- Institute: Institute for Machine Speech Processing (IMS)\\
104
- University: University of Stuttgart\\
105
- Contact: eva-maria.vecchi@ims.uni-stuttgart.de
106
- _________________________________________________________________________________________
107
-
108
- ### Description of the research study
109
-
110
- In this study, we investigate [...]
111
-
112
- The intended use of the results of this study includes [...]
113
-
114
- **Time required:** Your participation will take up to an estimated [...] hours. The time required may vary on an individual basis.
115
-
116
- **Risks and benefits:** The risks to your participation in this online survey are those associated with basic computer tasks, including boredom, fatigue, mild stress, or breach of confidentiality. Some of the topics discussed in the online posts to be annotated may include violence, suicide or rape. The only benefit to you is the learning experience from participating in a research study. The benefit to society is the contribution to scientific knowledge
117
-
118
- **Compensation:** You will be compensated for participating in this study. If you are interested, we will also be more than happy to share more information about our research with you.
119
-
120
- **Voluntary participation:** Your participation in this study is voluntary. It is your decision whether or not to participate in this study. If you decide to participate in this study, you will be asked to confirm this consent form ("I agree."). Even after signing the consent form, you can withdraw from participation at any time and without giving any reason. Partial data will not be analysed.
121
-
122
- **Confidentiality:** Your responses to this experiment will be anonymous. Please do not share any
123
- Information that can be used to identify you. The researcher(s) will make every effort to maintain your confidentiality.
124
-
125
- **Contact:** If at any time you have questions about this study or would like to report any adverse effects due to this study, please contact the researcher(s).
126
-
127
- **Trigger Warning:** [...]
128
-
129
- ### Consent:
130
- Please indicate, in the box below, that you are at least 18 years old, have read and understood this consent form, are comfortable using the English language to complete the survey, and you agree to participate in this online research survey.
131
-
132
- - *I am age 18 or older.*
133
- - *I have read this consent form or had it read to me.*
134
- - *I am comfortable using the English language to participate in this survey.*
135
- - *I agree to participate in this research and I want to continue with the survey.*
136
- '''
137
- guidelines_text = 'Please read <a href="https://tinyurl.com/56ryck9h">the guidelines</a>'
138
- study_code = os.environ.get("STUDY_CODE2")
139
- failed_sanity_check_code = os.environ.get("FAILED_CODE2")
140
- redirect_url = f'https://app.prolific.com/submissions/complete?cfc={study_code}'
141
- failed_redirect_url = f'https://app.prolific.com/submissions/complete?cfc={failed_sanity_check_code}'
142
- annotation_guidelines_fields: List[Field] = [
143
- Field(name="annotation_guidelines", type="radio", title="Did you read the guidelines?", mandatory=True,
144
- other_params={'labels': ['Yes, in detail, and I understand the study',
145
- 'Yes, in detail, but still confused',
146
- 'Yes, I skimmed it',
147
- 'I will read it later',
148
- 'No, not interested in reading them',
149
- 'I can not open the link',
150
- ],
151
- 'accepted_values': [0]}),
152
- ]
153
-
154
- intro_fields: List[Field] = [
155
- Field(type="container", title="**Introductory Questions**", children=[
156
- Field(name="intro_role", type="radio", title="What experience do you have with online discussion moderation?",
157
- other_params={'labels': ['Moderator for online deliberative platforms',
158
- 'Moderator in r/ChangeMyView',
159
- 'Moderator for newspaper digital platforms',
160
- 'Academic researcher in the field of e-Democracy, deliberative discourse, computational argumentation, or the like',
161
- 'Frequent contributor to moderated discussions online, eg CMV or similar',
162
- 'Other'],
163
- 'accepted_values': [0,1,2,3]}),
164
- Field(name="intro_moderation_goals", type="textarea", title="As a moderator, what are your goals/objectives for the comment section?"),
165
- Field(name="intro_experience", type="textarea", title="What do you feel contributes to a good experience for the users/discussion?"),
166
- Field(name="intro_valuable_comment", type="textarea", title="What makes a comment or contribution valuable?"),
167
- Field(name="intro_bad_comment", type="textarea", title="What makes a comment or contribution of poor quality, unconstructive or detrimental to the discussion?"),
168
- ]),
169
- ]
170
-
171
-
172
- concluding_fields: List[Field] = [
173
- Field(type="container", title="**Concluding Questions**", children=[
174
- Field(name="conc_general_ease", type="likert_radio", title="**Determining when an instance would indeed benefit from moderator intervention was straightforward (easy to annotate).**"),
175
- Field(name="conc_guess_mod_prediction", type="likert_radio", title="**I had a pretty clear idea of which instances were predicted to need moderation by your tool, and which were not.**"),
176
- Field(name="conc_visual_useful", type="likert_radio", title="**The visualization of properties was helpful in making my assessments.**"),
177
- Field(name="conc_overall_usefullness", type="likert_radio", title="**Having a tool that accurately predicts and flags comments needing moderation will significantly aid in my tasks.**"),
178
- Field(name="conc_decision_making", type="textaread", title="**Would a tool with accurate predictions assist you in making more informed moderation decisions? How so?**"),
179
- Field(name="conc_bottleneck", type="textarea", title="**What do you feel is the largest bottleneck (or obstacle) you face in online discussion moderation?**"),
180
- Field(name="conc_needs", type="textarea", title="**Beyond the goals of this research and annotation task, what assistance do you feel computational tools (like AI) could provide to your task?**"),
181
- ]),
182
- ]
183
-
184
- end_fields: List[Field] = [
185
- Field(type="container", title="**How can we reach you for compensation?**", children=[
186
- Field(name="email", type="text", title="Enter an email address where we can send you the payment or voucher. \n \n *Note: Without this, we cannot compensate you for your contribution to our research.*"),
187
- Field(name="payment_type", type="radio", title="Select reimbursment method:",
188
- other_params={'labels': ['PayPal',
189
- 'Amazon Voucher']}),
190
- Field(name="amazon_store", type="radio", title="Select which amazon store for your voucher:",
191
- other_params={'labels': ['amazon.com',
192
- 'amazon.co.uk',
193
- 'amazon.de',
194
- 'amazon.au',
195
- 'Other']}, mandatory=False),
196
- Field(name="amazon_store_other", type="text", title="If other, please specify.", mandatory=False),
197
- ]),
198
- ]
199
-
200
- fields: List[Field] = [
201
- Field(name="patient", type="input_col", title="**Patient::**"),
202
- Field(type="expander", title="**Preceeding Comment:** *(expand)*", children=[
203
- Field(name="dialogue_name", type="input_col", title=""),
204
- ]),
205
-
206
- Field(type="container", title="**Session-/Patient-Specific Properties**", children=[
207
- Field(name="to_moderate", type="y_n_radio",
208
- title="Explicit mention of clinical diagnosis?", mandatory=True),
209
- Field(name="priority_level", type="likert_radio",
210
- title="Emotional State", other_params={'labels': priority_labels}, mandatory=True),
211
- ]),
212
-
213
- Field(type="container", title="**Rupture-Specific Properties**", children=[
214
- Field(name="mod_function", type="multiselect",
215
- title="What type of rupture markers are found? *(Multiple selection possible)*",
216
- mandatory=False, following_mandatory_values=['Other (please specify)']),
217
- Field(name="mod_function_other", type="text", title="*If Other, please specify:*", mandatory=False),
218
- Field(name="rupture_line", type="text", title="What lines demonstrate the rupture markers you notice?", mandatory=False),
219
- ]),
220
-
221
- Field(type="container", title="**True-To-Patient-Prompt Properties**", children=[
222
- Field(name="helpful", type="y_n_radio",
223
- title="Did the patient remain true to the provided patient prompt?", mandatory=True,
224
- following_mandatory_values=[1]),
225
- ]),
226
-
227
- Field(type="container", title="**Other**", children=[
228
- Field(name="other_comments", type="text", title="Please provide any additional details or information: *(optional)*", mandatory=False),
229
- ]),
230
- ]
231
- url_conditional_fields = [
232
- Field(name="skip", type="skip_checkbox",
233
- title="*I am uncomfortable annotating this text and voluntarily skip this instance*", mandatory=False)
234
- ]
235
- INPUT_FIELD_DEFAULT_VALUES = {'slider': 0,
236
- 'text': '',
237
- 'textarea': '',
238
- 'checkbox': False,
239
- 'radio': None,
240
- 'select_slider': 0,
241
- 'multiselect': [],
242
- 'likert_radio': None,
243
- 'y_n_radio': None}
244
- SHOW_HELP_ICON = False
245
- SHOW_VALIDATION_ERROR_MESSAGE = True
246
-
247
- ########################################################################################
248
- if filesystem == 'hf':
249
- HF_TOKEN = os.environ.get("HF_TOKEN_READ_WRITE")
250
- print("is none?", HF_TOKEN is None)
251
- hf_fs = HfFileSystem(token=HF_TOKEN)
252
- else:
253
- hf_fs = LocalFileSystem()
254
-
255
- def get_start_index():
256
- if hf_fs.exists(output_repo_path + '/' + get_base_path()):
257
- files = hf_fs.ls(output_repo_path + '/' + get_base_path())
258
- return len(files) - 1
259
- else:
260
- return -2
261
-
262
- def read_data():
263
- with hf_fs.open(input_repo_path + '/' + to_annotate_file_name) as f:
264
- return pd.read_csv(f)
265
-
266
- def read_saved_data():
267
- _path = get_path()
268
- if hf_fs.exists(output_repo_path + '/' + _path):
269
- with hf_fs.open(output_repo_path + '/' + _path) as f:
270
- try:
271
- return json.load(f)
272
- except json.JSONDecodeError as e:
273
- print(e)
274
- return None
275
-
276
- # Write a remote file
277
- def save_data(data):
278
- if not hf_fs.exists(f"{output_repo_path}/{get_base_path()}"):
279
- hf_fs.mkdir(f"{output_repo_path}/{get_base_path()}")
280
- with hf_fs.open(f"{output_repo_path}/{get_path()}", "w") as f:
281
- f.write(json.dumps(data))
282
-
283
-
284
- def get_base_path():
285
- return f"{st.session_state.user_id}"
286
-
287
- def get_path():
288
- return f"{get_base_path()}/{st.session_state.current_index}.json"
289
-
290
- def display_dialogue(dialogue_path):
291
- dialogue_text = load_text(dialogue_path)
292
- st.markdown(
293
- f"<details><summary><b>Annotation Guidelines</b></summary><div>{dialogue_text}</div></details><br>",
294
- unsafe_allow_html=True)
295
- #with open(dialogue_path, "r", encoding="utf-8") as f:
296
- # lines = f.readlines()
297
- #for i, line in enumerate(lines, start=1):
298
- # st.write(f"{i:03d}: {line.strip()}")
299
-
300
- def display_image(image_path):
301
- with hf_fs.open(image_path) as f:
302
- img = Image.open(f)
303
- st.image(img, caption='8 most contributing properties', use_column_width=True)
304
-
305
- def load_text(file):#dialogue
306
- with open(file, "r") as file:
307
- consent_text = file.read()
308
- return consent_text
309
-
310
- #################################### Streamlit App ####################################
311
-
312
- # Function to navigate rows
313
- def navigate(index_change):
314
- st.session_state.current_index += index_change
315
- # only works consistently if done before rerun
316
- js = '''
317
- <script>
318
- var body = window.parent.document.querySelector(".main");
319
- body.scrollTop = 0;
320
- window.scrollY = 0;
321
- </script>
322
- '''
323
- st.components.v1.html(js, height=0)
324
- # https://discuss.streamlit.io/t/click-twice-on-button-for-changing-state/45633/2
325
-
326
- # disable text input enter to submit
327
- # https://discuss.streamlit.io/t/text-input-how-to-disable-press-enter-to-apply/14457/6
328
- components.html(
329
- """
330
- <script>
331
- const inputs = window.parent.document.querySelectorAll('input');
332
- inputs.forEach(input => {
333
- input.addEventListener('keydown', function(event) {
334
- if (event.key === 'Enter') {
335
- event.preventDefault();
336
- }
337
- });
338
- });
339
- </script>
340
- """,
341
- height=0
342
- )
343
-
344
- #st.experimental_rerun()
345
- st.rerun()
346
-
347
- def show_field(f: Field, index: int, data_collected):
348
- if f.type not in INPUT_FIELD_DEFAULT_VALUES.keys():
349
- st.session_state.following_mandatory = False
350
- match f.type:
351
- case 'input_col':
352
- value = st.session_state.data.iloc[index][f.name]
353
- if value and value is not np.nan:
354
- st.write(f.title)
355
- if f.name == 'image_name':
356
- display_image(os.path.join(input_repo_path, 'images', value))
357
- elif f.name == 'dialogue_name':
358
- #display_dialogue(os.path.join(input_repo_path, 'dialogues', value))
359
- display_dialogue(os.path.join(input_repo_path, value))
360
- else:
361
- st.write(value)
362
- case 'markdown':
363
- st.markdown(f.title)
364
- case 'expander' | 'container':
365
- with (st.expander(f.title) if f.type == 'expander' else st.container(border=True)):
366
- if f.type == 'container':
367
- st.markdown(f.title)
368
- for child in f.children:
369
- show_field(child, index, data_collected)
370
- case 'skip_checkbox':
371
- st.checkbox(f.title, key=f.name, value=False)
372
- else:
373
- key = f.name + str(index)
374
- st.session_state.data_inputs_keys.append(f.name)
375
- value = st.session_state[key] if key in st.session_state else \
376
- (data_collected[f.name] if data_collected else INPUT_FIELD_DEFAULT_VALUES[f.type])
377
- if not SHOW_HELP_ICON:
378
- f.title = f'**{f.title}**\n\n{f.help}' if f.help else f.title
379
-
380
- validation_error = False
381
-
382
- # form is not displayed for first time
383
- if st.session_state.form_displayed == st.session_state.current_index:
384
- if st.session_state.following_mandatory and f.skip_mandatory:
385
- st.session_state.following_mandatory = False
386
- if f.following_mandatory_values and st.session_state[key] in f.following_mandatory_values:
387
- st.session_state.following_mandatory = True
388
- if f.mandatory or st.session_state.following_mandatory:
389
- if st.session_state[key] == INPUT_FIELD_DEFAULT_VALUES[f.type]:
390
- st.session_state.valid = False
391
- validation_error = True
392
- elif f.following_mandatory_values and st.session_state[key] in f.following_mandatory_values:
393
- st.session_state.following_mandatory = True
394
-
395
- # check for any unaccepted values
396
- if (
397
- (f.other_params.get('accepted_values') and
398
- value not in f.other_params.get('accepted_values')) or
399
- (f.other_params.get('accepted_values_per_sample') and
400
- index in f.other_params.get('accepted_values_per_sample') and
401
- value not in f.other_params.get('accepted_values_per_sample').get(index))
402
- ):
403
- st.session_state.unacceptable_response = True
404
-
405
- if f.mandatory or st.session_state.following_mandatory:
406
- f.title += " :red[* required!]" if (validation_error and not SHOW_VALIDATION_ERROR_MESSAGE) else' :red[*]'
407
- f.help = None
408
-
409
-
410
- match f.type:
411
- case 'checkbox':
412
- st.checkbox(f.title,
413
- key=key,
414
- value=value, help=f.help)
415
- case 'radio':
416
- labels = default_labels if not f.other_params.get('labels') else f.other_params.get('labels')
417
- st.radio(f.title,
418
- options=range(len(labels)),
419
- format_func=lambda x: labels[x],
420
- key=key,
421
- index=value, help=f.help, horizontal=False)
422
- case 'slider':
423
- st.slider(f.title,
424
- min_value=0, max_value=6, step=1,
425
- key=key,
426
- value=value, help=f.help)
427
- case 'select_slider':
428
- labels = default_labels if not f.other_params.get('labels') else f.other_params.get('labels')
429
- st.select_slider(f.title,
430
- options=[0, 20, 40, 60, 80, 100],
431
- format_func=lambda x: labels[x // 20],
432
- key=key,
433
- value=value, help=f.help)
434
- case 'multiselect':
435
- choices = default_choices if not f.other_params.get('choices') else f.other_params.get('choices')
436
- st.multiselect(f.title,
437
- options = choices,
438
- format_func=lambda x: x,
439
- key=key, max_selections=3,
440
- default=value, help=f.help)
441
- case 'likert_radio':
442
- labels = default_labels if not f.other_params.get('labels') else f.other_params.get('labels')
443
- st.radio(f.title,
444
- options=[0, 1, 2, 3, 4],
445
- format_func=lambda x: labels[x],
446
- key=key,
447
- index=value, help=f.help, horizontal=True)
448
- case 'y_n_radio':
449
- labels = yes_no_labels if not f.other_params.get('labels') else f.other_params.get('labels')
450
- st.radio(f.title,
451
- options=[0, 1],
452
- format_func=lambda x: labels[x],
453
- key=key,
454
- index=value, help=f.help, horizontal=True)
455
- case 'text':
456
- st.text_input(f.title, key=key, value=value, max_chars=None)
457
- case 'textarea':
458
- st.text_area(f.title, key=key, value=value, max_chars=None)
459
-
460
- if validation_error:
461
- st.session_state.unacceptable_response = False
462
- st.error(f"Mandatory field")
463
-
464
- def show_fields(fields: List[Field]):
465
- st.session_state.valid = True
466
- index = st.session_state.current_index
467
- data_collected = read_saved_data()
468
- st.session_state.data_inputs_keys = []
469
- st.session_state.following_mandatory = False
470
-
471
- for field in fields:
472
- show_field(field, index, data_collected)
473
-
474
- submitted = st.form_submit_button("Submit")
475
- if submitted:
476
- if 'unacceptable_response' in st.session_state and st.session_state.unacceptable_response:
477
- prep_and_save_data(index, ('skip' in st.session_state and st.session_state['skip']))
478
- st.rerun()
479
- skip_sample = ('skip' in st.session_state and st.session_state['skip'])
480
- if not skip_sample and not st.session_state.valid:
481
- st.error("Please fill in all mandatory fields")
482
- # st.rerun() # filed-out values are not shown otherwise
483
- else:
484
- with st.spinner(text="saving"):
485
- prep_and_save_data(index, skip_sample)
486
- st.success("Feedback submitted successfully!")
487
- navigate(1)
488
-
489
- st.session_state.form_displayed = st.session_state.current_index
490
-
491
- def prep_and_save_data(index, skip_sample):
492
- save_data({
493
- 'user_id': st.session_state.user_id,
494
- 'index': st.session_state.current_index,
495
- **(st.session_state.data.iloc[index][COLS_TO_SAVE].to_dict() if 0 <= index < len(st.session_state.data) else {}),
496
- **{k: st.session_state[k + str(index)] for k in st.session_state.data_inputs_keys},
497
- 'skip': skip_sample
498
- })
499
-
500
-
501
-
502
- # Title of the app
503
- st.title("Therapy Session Annotation")
504
-
505
-
506
- st.markdown(
507
- """<style>
508
- div[data-testid="stMarkdownContainer"] > p {
509
- font-size: 1rem;
510
- }
511
- section.main > div {max-width:60rem}
512
- </style>"""
513
- , unsafe_allow_html=True)
514
-
515
-
516
- def add_annotation_guidelines():
517
- st.write(f"Username is {st.session_state.user_id[4:] if st.session_state.user_id.startswith('PID_') else st.session_state.user_id}")
518
- st.markdown(
519
- "<details open><summary><b>Annotation Guidelines</b></summary>" + guidelines_text + "</details><br>"
520
- , unsafe_allow_html=True)
521
-
522
-
523
- if 'unacceptable_response' in st.session_state and st.session_state.unacceptable_response:
524
- add_annotation_guidelines()
525
- st.error("You are not eligible for this study. Thank you for your time!" +
526
- ("" if st.session_state.current_index < 0 else
527
- " You will receive a small compensation for your contribution up to now. "
528
- "Please return to the study and copy/paste this code: " + failed_sanity_check_code))
529
- st.stop()
530
-
531
- # Load the data to annotate
532
- if 'data' not in st.session_state:
533
- st.session_state.data = read_data()
534
-
535
- # user id
536
- user_id_from_url = get_param_from_url("user_id")
537
- if user_id_from_url:
538
- st.session_state.user_id = user_id_from_url
539
-
540
- # current index
541
- if 'current_index' not in st.session_state:
542
- start_index = get_start_index()
543
- if start_index < len(st.session_state.data)-1:
544
- st.session_state.current_index = start_index
545
- else:
546
- st.session_state.current_index = start_index+1
547
- st.session_state.form_displayed = -2
548
-
549
- if get_param_from_url('show_extra_fields'):
550
- fields += url_conditional_fields
551
- else:
552
- fields += url_conditional_fields
553
- def add_validated_submit(fields, message):
554
- st.session_state.form_displayed = st.session_state.current_index
555
- if st.form_submit_button("Submit"):
556
- if all(not x for x in fields):
557
- st.error(message)
558
- else:
559
- navigate(1)
560
-
561
- def add_checked_submit():
562
- check = st.checkbox('I agree', key='consent')
563
- add_validated_submit([check], "Please agree to give your consent to proceed")
564
-
565
- if 'go_to' not in st.session_state:
566
- st.session_state.go_to = 0
567
-
568
- if st.session_state.current_index == -2:
569
- with st.form("data_form"):
570
- st.markdown(consent_text)
571
- add_checked_submit()
572
-
573
- elif st.session_state.current_index == -1:
574
- if st.session_state.get('user_id'):
575
- navigate(1)
576
- else:
577
- with st.form("data_form"):
578
- st.session_state.user_id = st.text_input('User ID', value=user_id_from_url)
579
- add_validated_submit([st.session_state.user_id], "Please enter a valid user ID")
580
-
581
- #elif st.session_state.current_index == -1:
582
- # add_annotation_guidelines()
583
- # with st.form("intro_form"):
584
- # show_fields(intro_fields)
585
-
586
- elif st.session_state.current_index < len(st.session_state.data):
587
- add_annotation_guidelines()
588
- with st.form("data_form"+str(st.session_state.current_index)):
589
- show_fields(fields)
590
-
591
- elif st.session_state.current_index == len(st.session_state.data):
592
- add_annotation_guidelines()
593
- with st.form("concluding_form"):
594
- show_fields(concluding_fields)
595
-
596
- elif st.session_state.current_index == len(st.session_state.data)+1:
597
- add_annotation_guidelines()
598
- with st.form("end_form"):
599
- show_fields(end_fields)
600
-
601
- else:
602
- st.write(f"**Thank you for taking part in this study!** \n \n [Click here]({redirect_url}) to complete the study or copy and paste this code back to finish the study: **{study_code}**")
603
-
604
- # Navigation buttons
605
- if 0 < st.session_state.current_index <= len(st.session_state.data):
606
- if st.button("Previous"):
607
- navigate(-1)
608
-
609
- if 0 <= st.session_state.current_index < len(st.session_state.data):
610
- st.write(f"Page {st.session_state.current_index + 1} out of {len(st.session_state.data)}")
611
-
612
-
613
- st.markdown(
614
- """<style>
615
- div[data-testid="InputInstructions"] {
616
- visibility: hidden;
617
- }
618
- </style>""", unsafe_allow_html=True
619
- )
620
-