File size: 26,410 Bytes
c43652c
 
013edfc
 
c43652c
 
3848935
c43652c
 
3848935
c43652c
 
effd9e4
3848935
c43652c
 
 
 
 
effd9e4
 
 
c43652c
7c741ef
52058f8
c43652c
 
3848935
 
c43652c
 
effd9e4
 
 
 
3848935
15bfc60
3848935
87ac987
495141a
3848935
 
 
 
 
fc84136
e1385b5
c43652c
b304a75
 
9b8fa34
3cfa329
 
b304a75
 
0521783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c38a618
e7c4848
0521783
8c46379
 
 
9f46364
13360c8
 
 
 
 
92c1ba9
 
137b465
6ca0272
137b465
 
 
 
01f10fd
6ca0272
01f10fd
 
 
137b465
 
6ca0272
137b465
a19e3af
137b465
 
 
29dc8d8
137b465
01f10fd
137b465
01f10fd
137b465
01f10fd
137b465
01f10fd
137b465
 
01f10fd
137b465
01f10fd
137b465
6ca0272
d340bce
8d4af47
b87cd4b
 
 
 
137b465
5aa9125
695baf2
a5c4ad0
3848935
 
 
 
 
 
 
 
 
 
 
 
 
d4f42d9
 
1c3aa97
63e180e
 
 
 
1c3aa97
d4f42d9
92c1ba9
a2d65cf
 
e14ee0e
a2d65cf
 
 
 
c43652c
117ae00
 
 
44c502a
c43652c
0d497f6
c43652c
50acbda
cecbbbd
237868c
9a0677e
2857b09
 
5e721ae
92c1ba9
 
 
2857b09
b4da7e9
06f190d
8ce15da
92c1ba9
0521783
 
df7d87a
79a6d1c
06f190d
0521783
92c1ba9
13360c8
cecbbbd
9f46364
13360c8
df7d87a
9f46364
2857b09
13360c8
 
96f3c27
872b99d
96f3c27
c43652c
7c741ef
209b31b
 
9b0f98b
38c83dc
d4bec53
cecbbbd
 
 
c43652c
effd9e4
c43652c
effd9e4
3848935
 
 
 
 
 
 
 
 
 
 
 
 
c43652c
3848935
 
 
c79cbc5
c43652c
 
 
 
 
 
 
 
 
3848935
c79cbc5
c43652c
 
3848935
 
c43652c
 
 
 
3848935
 
 
c43652c
3848935
c43652c
 
 
 
 
552382e
c43652c
 
 
 
 
 
effd9e4
 
 
10817d9
 
 
effd9e4
 
 
c43652c
effd9e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10817d9
b65a607
 
c43652c
a885e86
c43652c
effd9e4
c43652c
 
3848935
 
c43652c
3848935
 
 
 
c43652c
 
 
 
 
 
 
a885e86
3848935
 
c43652c
 
effd9e4
 
 
c43652c
 
effd9e4
 
3848935
 
 
 
effd9e4
 
 
 
 
3848935
 
 
 
 
 
 
 
 
 
 
 
 
effd9e4
 
 
3848935
c43652c
 
effd9e4
 
 
5e721ae
2857b09
3cfa329
effd9e4
 
c43652c
effd9e4
 
 
 
b304a75
 
effd9e4
 
 
 
 
36758e4
 
b86988b
a750fda
dc52e0d
effd9e4
9ff34e6
effd9e4
 
 
 
 
 
 
cecbbbd
 
 
3cfa329
cecbbbd
 
 
c43652c
e2055cc
c43652c
e2055cc
c43652c
effd9e4
3848935
effd9e4
c43652c
 
302cefa
effd9e4
302cefa
 
effd9e4
 
c79cbc5
302cefa
6273da8
302cefa
 
 
3848935
 
 
 
 
effd9e4
 
 
 
3848935
effd9e4
 
 
 
 
3848935
 
 
 
 
 
 
 
c43652c
3848935
c43652c
8193778
c43652c
effd9e4
c43652c
 
 
 
 
3848935
c43652c
 
 
3848935
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c43652c
 
3848935
 
 
6421e0a
 
 
c43652c
3848935
c43652c
3848935
 
effd9e4
 
3848935
 
 
d4f42d9
b0f4dd5
effd9e4
d4f42d9
b0f4dd5
 
d4f42d9
 
c43652c
3848935
b0f4dd5
 
 
 
1a02d46
 
 
d4f42d9
 
 
 
 
 
3848935
c43652c
 
d4f42d9
49d2940
 
6421e0a
49d2940
d4f42d9
 
effd9e4
d4f42d9
c43652c
 
d4f42d9
effd9e4
d4f42d9
 
a2d65cf
 
 
c79cbc5
d4f42d9
c79cbc5
d4f42d9
d479385
5a84846
d479385
 
46237a7
c43652c
 
 
9a76d33
6c882b4
8a76709
9a76d33
ec9d229
8a76709
9a76d33
ec9d229
 
5152041
ec9d229
816a7d7
8a76709
816a7d7
8a76709
 
6c882b4
65d9b9b
 
 
 
 
 
d479385
c43652c
 
 
 
 
 
c79cbc5
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
import json
import os
from dataclasses import dataclass, field
from typing import List, Optional, Dict
from PIL import Image

import numpy as np
import pandas as pd
import streamlit as st
from fsspec.implementations.local import LocalFileSystem
from huggingface_hub import HfFileSystem

import streamlit.components.v1 as components

@dataclass
class Field:
    type: str
    title: str
    name: str = None
    mandatory: bool = True
    # if value of field is in the list of those values, makes following siblings mandatory
    following_mandatory_values: list = False
    help: Optional[str] = None
    children: Optional[List['Field']] = None
    other_params: Optional[Dict[str, object]] = field(default_factory=lambda: {})

# Function to get user ID from URL
def get_param_from_url(param):
    user_id = st.query_params.get(param, "")
    return user_id


########################################################################################
# CHANGE THE FOLLOWING VARIABLES ACCORDING TO YOUR NEEDS

# 'local' or 'hf'. hf is for Hugging Face file system but has limits on the number of access per hour
filesystem = 'hf'
# path to repo or local file system TODO rename
input_repo_path = 'datasets/emvecchi/annotation'
output_repo_path = 'datasets/emvecchi/annotation'
# filesystem = 'local'
# path to repo or local file system
# input_repo_path = '/data/mod-gen-eval-pref'
# output_repo_path = '/data/mod-gen-eval-pref'

to_annotate_file_name = 'to_annotate.csv'  # CSV file to annotate
COLS_TO_SAVE = ['comment_id','comment','confidence_score']

agreement_labels = ['strongly disagree', 'disagree', 'neither agree no disagree', 'agree', 'strongly agree']
quality_labels = ['very poor', 'poor', 'acceptable', 'good', 'very good']
priority_labels = ['not a priority', 'low priority', 'neutral', 'moderate priority', 'high priority']
yes_no_labels = ['yes','no']
yes_no_other_labels = ['yes','no','other']
default_labels = agreement_labels

function_choices = ['Broadening Discussion', 
                    'Improving Comment Quality', 
                    'Content Correction', 
                    'Keeping Discussion on Topic', 
                    'Organizing Discussion', 
                    'Policing', 
                    'Resolving Site Use Issues', 
                    'Social Functions', 
                    'Other (please specify)']
property_choices = ['appropriateness',
                    'clarity',
                    'constructiveness', 
                    'common good',
                    'effectiveness',
                    'emotion', 
                    'impact',
                    'overall quality', 
                    'proposal',
                    'Q for justification',
                    'storytelling', 
                    'rationality', 
                    'reasonableness', 
                    'reciprocity', 
                    'reference',
                    'respect',
                    'moderation behavior',
                    'Other (please specify)']
assistance_choices = ['Expand the breadth of moderator role',
                    'Reduce my own bias',
                    #'Assist with recall',
                    'Avoids me missing relevant instances',
                    'Improve speed of moderation tasks',
                    'Manage prioritization of comments to consider',
                    'Visualization of properties narrows down moderator contribution',
                    'Other (please specify)']
                    
default_choices = function_choices

consent_text = '''
## Consent Form

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.
________________________________________________________________________________________

Project title: Moderator Intervention Prediction\\
Researchers: E.M. Vecchi, N. Falk, I. Jundi, G. Lapesa\\
Institute: Institute for Machine Speech Processing (IMS)\\
University: University of Stuttgart\\
Contact: eva-maria.vecchi@ims.uni-stuttgart.de
_________________________________________________________________________________________

### Description of the research study

In this study, we investigate an approach to assist expert moderators in online discussion platforms by automatically identifying comments in need of moderation. The annotators' task is to evaluate whether a comment returned by our system are indeed requires moderator intervention, and assess the impact such a system would have on the task of moderation.

The intended use of the results of this study includes an analysis as well as processed versions of the collected data in the context of a publicly available scientific publication.

**Time required:** Your participation will take up to an estimated 8 hours. The time required may vary on an individual basis.

**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

**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.

**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.

**Confidentiality:** Your responses to this experiment will be anonymous. Please do not share any
Information that can be used to identify you. The researcher(s) will make every effort to maintain your confidentiality.

**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).

**Trigger Warning:** The texts included in this study are produced in an online debate forum and some topics that are discussed, how they are discussed, and user perspectives may be uncomfortable or sensitive. First, all texts included here do not represent the views of the researchers conducting the study. Secondly, we provide the option [described in detail in the guidelines provided in the next step] to avoid having to annotate any instance that is problematic or uncomfortable for the annotator without penalty of compensation.

### Consent:
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.

- *I am age 18 or older.*
- *I have read this consent form or had it read to me.*
- *I am comfortable using the English language to participate in this survey.*
- *I agree to participate in this research and I want to continue with the survey.*
'''
guidelines_text = 'Please read <a href="https://acrobat.adobe.com/id/urn:aaid:sc:EU:1a1347b0-3423-49ee-aa28-87679f8a69c0">the guidelines</a>'
study_code = 'CE552C7F'
failed_sanity_check_code = 'C17NFPW5'
redirect_url = f'https://app.prolific.com/submissions/complete?cfc={study_code}'

annotation_guidelines_fields: List[Field] = [
    Field(name="annotation_guidelines", type="radio", title="Did you read the guidelines?", mandatory=True,
          other_params={'labels': ['Yes, in detail, and I understand the study',
                                   'Yes, in detail, but still confused',
                                   'Yes, I skimmed it',
                                   'I will read it later',
                                   'No, not interested in reading them',
                                   'I can not open the link',
                                   ],
                        'accepted_values': [0]}),
]

intro_fields: List[Field] = [
    Field(type="container", title="**Introductory Questions**", children=[
        Field(name="intro_moderation_goals", type="textarea", title="As a moderator, what are your goals/objectives for the comment section?"),
        Field(name="intro_experience", type="textarea", title="What do you feel contributes to a good experience for the users/discussion?"),
        Field(name="intro_valuable_comment", type="textarea", title="What makes a comment or contribution valuable?"),
        Field(name="intro_bad_comment", type="textarea", title="What makes a comment or contribution of poor quality, unconstructive or detrimental to the discussion?"),
    ]),
]

end_fields: List[Field] = [
    Field(type="container", title="**Thank you for taking part in this study!**", children=[
        Field(name="email", type="textarea", title="Enter an email address where we can send you the voucher. **Without this, we cannot compensate you for your contribution to our research.**"),
    ]),
]


fields: List[Field] = [
    Field(name="topic", type="input_col", title="**Topic:**"),
    Field(type="expander", title="**Preceeding Comment:** *(expand)*", children=[
        Field(name="parent_comment", type="input_col", title=""),
    ]),
    Field(name="comment", type="input_col", title="**Comment:**"),
    Field(name="image_name", type="input_col", title=""),# "**Visualization of high contributing properties:**"),

    Field(type="container", title="**Need for Moderation**", children=[
        Field(name="to_moderate", type="y_n_radio",
                   title="Do feel this comment/discussion would benefit from moderator intervention?", mandatory=True),
        Field(name="priority_level", type="likert_radio",
                   title="With what level of **priority** would you need to interact with this comment?", other_params={'labels': priority_labels},
                     mandatory=True),
    ]),

    Field(type="container", title="**Moderation Function**", children=[
        Field(name="mod_function", type="multiselect",
                     title="What type of moderation function is needed here? *(Multiple selection possible)*",
                     mandatory=True),
        Field(name="mod_function_other", type="text", title="*If Other, please specify:*", mandatory=False),
    ]),

    Field(type="container", title="**Contributing properties**", children=[
        Field(name="relevant_properties", type="multiselect",
                title="Which property(s) is most impactful in your assessment? *(Multiple selection possible)*", 
                other_params={'choices': property_choices}, mandatory=True),
        Field(name="relevant_properties_other", type="text", title="*If Other, please specify:*", mandatory=False),
    ]),
    
    Field(type="container", title="**Moderator Assistance**", children=[
        Field(name="helpful", type="y_n_radio",
                title="If this comment/discussion was flagged to you, would it be helpful in your task of moderation?", mandatory=True, following_mandatory_values=[0]),
        Field(name="mod_assistance", type="multiselect",
                title="If yes, please motivate the benefit it would contribute to the task. *(Multiple selection possible)*", 
                other_params={'choices': assistance_choices}),
        Field(name="mod_assistance_other", type="text", title="*If Other, please specify:*", mandatory=False),
    ]),
    
    Field(type="container", title="**Other**", children=[
        Field(name="other_comments", type="text", title="Please provide any additional details or information: *(optional)*", mandatory=False),
    ]),
]
INPUT_FIELD_DEFAULT_VALUES = {'slider': 0,
                              'text': '',
                              'textarea': '',
                              'checkbox': False,
                              'radio': None,
                              'select_slider': 0,
                              'multiselect': None,
                              'likert_radio': None,
                              'y_n_radio': None}
SHOW_HELP_ICON = False
SHOW_VALIDATION_ERROR_MESSAGE = True

########################################################################################
if filesystem == 'hf':
    HF_TOKEN = os.environ.get("HF_TOKEN_WRITE2")
    print("is none?", HF_TOKEN is None)
    hf_fs = HfFileSystem(token=HF_TOKEN)
else:
    hf_fs = LocalFileSystem()

def get_start_index():
    if hf_fs.exists(output_repo_path + '/' + get_base_path()):
        files = hf_fs.ls(output_repo_path + '/' + get_base_path())
        return len(files) - 2
    else:
        return -3

def read_data():
    with hf_fs.open(input_repo_path + '/' + to_annotate_file_name) as f:
        return pd.read_csv(f)

def read_saved_data():
    _path = get_path()
    if hf_fs.exists(output_repo_path + '/' + _path):
        with hf_fs.open(output_repo_path + '/' + _path) as f:
            try:
                return json.load(f)
            except json.JSONDecodeError as e:
                print(e)
    return None
    

# Write a remote file
def save_data(data):
    if not hf_fs.exists(f"{output_repo_path}/{get_base_path()}"):
        hf_fs.mkdir(f"{output_repo_path}/{get_base_path()}")
    with hf_fs.open(f"{output_repo_path}/{get_path()}", "w") as f:
        f.write(json.dumps(data))


def get_base_path():
    return f"{st.session_state.user_id}"

def get_path():
    return f"{get_base_path()}/{st.session_state.current_index}.json"


def display_image(image_path):
    with hf_fs.open(image_path) as f:
        img = Image.open(f)
        st.image(img, caption='8 most contributing properties', use_column_width=True)
        
#################################### Streamlit App ####################################

# Function to navigate rows
def navigate(index_change):
    st.session_state.current_index += index_change
    # only works consistently if done before rerun
    js = '''
    <script>
            var body = window.parent.document.querySelector(".main");
            body.scrollTop = 0;
            window.scrollY = 0;
    </script>
    '''
    st.components.v1.html(js, height=0)
    # https://discuss.streamlit.io/t/click-twice-on-button-for-changing-state/45633/2

    # disable text input enter to submit
    # https://discuss.streamlit.io/t/text-input-how-to-disable-press-enter-to-apply/14457/6
    components.html(
        """
        <script>
        const inputs = window.parent.document.querySelectorAll('input');
        inputs.forEach(input => {
            input.addEventListener('keydown', function(event) {
                if (event.key === 'Enter') {
                    event.preventDefault();
                }
            });
        });
        </script>
        """,
        height=0
    )

    #st.experimental_rerun()
    st.rerun()

def show_field(f: Field, index: int, data_collected):
    if f.type not in INPUT_FIELD_DEFAULT_VALUES.keys():
        st.session_state.following_mandatory = False
        match f.type:
            case 'input_col':
                value = st.session_state.data.iloc[index][f.name]
                if value and value is not np.nan:
                    st.write(f.title)
                    if f.name == 'image_name':
                        display_image(os.path.join(input_repo_path, 'images', value))
                    else:
                        st.write(value)
            case 'markdown':
                st.markdown(f.title)
            case 'expander' | 'container':
                with (st.expander(f.title) if f.type == 'expander' else st.container(border=True)):
                    if f.type == 'container':
                        st.markdown(f.title)
                    for child in f.children:
                        show_field(child, index, data_collected)
            case 'skip_checkbox':
                st.checkbox(f.title, key=f.name, value=False)
    else:
        key = f.name + str(index)
        st.session_state.data_inputs_keys.append(f.name)
        value = st.session_state[key] if key in st.session_state else \
            (data_collected[f.name] if data_collected else INPUT_FIELD_DEFAULT_VALUES[f.type])
        if not SHOW_HELP_ICON:
            f.title = f'**{f.title}**\n\n{f.help}' if f.help else f.title

        validation_error = False

        # form is not displayed for first time
        if st.session_state.form_displayed == st.session_state.current_index:
            if f.mandatory or st.session_state.following_mandatory:
                if st.session_state[key] == INPUT_FIELD_DEFAULT_VALUES[f.type]:
                    st.session_state.valid = False
                    validation_error = True
                elif f.following_mandatory_values and st.session_state[key] in f.following_mandatory_values:
                    st.session_state.following_mandatory = True

        
            # check for any unaccepted values
            if (
                    (f.other_params.get('accepted_values') and
                     value not in f.other_params.get('accepted_values')) or
                    (f.other_params.get('accepted_values_per_sample') and
                     index in f.other_params.get('accepted_values_per_sample') and
                     value not in f.other_params.get('accepted_values_per_sample').get(index))
            ):
                st.session_state.unacceptable_response = True

        if f.mandatory or st.session_state.following_mandatory:
            f.title += " :red[* required!]" if (validation_error and not SHOW_VALIDATION_ERROR_MESSAGE) else' :red[*]'
        f.help = None

        
        match f.type:
            case 'checkbox':
                st.checkbox(f.title,
                            key=key,
                            value=value, help=f.help)
            case 'radio':
                st.radio(f.title,
                            ["yes","no"],
                            key=key,
                            help=f.help)
            case 'slider':
                st.slider(f.title,
                          min_value=0, max_value=6, step=1,
                          key=key,
                          value=value, help=f.help)
            case 'select_slider':
                labels = default_labels if not f.other_params.get('labels') else f.other_params.get('labels')
                st.select_slider(f.title,
                                 options=[0, 20, 40, 60, 80, 100],
                                 format_func=lambda x: labels[x // 20],
                                 key=key,
                                 value=value, help=f.help)
            case 'multiselect':
                choices = default_choices if not f.other_params.get('choices') else f.other_params.get('choices')
                st.multiselect(f.title,
                                options = choices,
                                format_func=lambda x: x,
                                key=key, max_selections=3,
                                default=value, help=f.help)
            case 'likert_radio':
                labels = default_labels if not f.other_params.get('labels') else f.other_params.get('labels')
                st.radio(f.title,
                         options=[0, 1, 2, 3, 4],
                         format_func=lambda x: labels[x],
                         key=key,
                         index=value, help=f.help, horizontal=True)
            case 'y_n_radio':
                labels = yes_no_labels if not f.other_params.get('labels') else f.other_params.get('labels')
                st.radio(f.title,
                         options=[0, 1],
                         format_func=lambda x: labels[x],
                         key=key,
                         index=value, help=f.help, horizontal=True)
            case 'text':
                st.text_input(f.title, key=key, value=value, max_chars=None)
            case 'textarea':
                st.text_area(f.title, key=key, value=value, max_chars=None)

        if validation_error:
            st.session_state.unacceptable_response = False
            st.error(f"Mandatory field")


def show_fields(fields: List[Field]):
    st.session_state.valid = True
    index = st.session_state.current_index
    data_collected = read_saved_data()
    st.session_state.data_inputs_keys = []
    st.session_state.following_mandatory = False

    for field in fields:
        show_field(field, index, data_collected)

    submitted = st.form_submit_button("Submit")
    if submitted:
        if 'unacceptable_response' in st.session_state and st.session_state.unacceptable_response:
            prep_and_save_data(index, ('skip' in st.session_state and st.session_state['skip']))
            st.rerun()
        skip_sample = ('skip' in st.session_state and st.session_state['skip'])
        if not skip_sample and not st.session_state.valid:
            st.error("Please fill in all mandatory fields")
            # st.rerun() # filed-out values are not shown otherwise
        else:
            with st.spinner(text="saving"):
                prep_and_save_data(index, skip_sample)
            st.success("Feedback submitted successfully!")
            navigate(1)

    st.session_state.form_displayed = st.session_state.current_index

def prep_and_save_data(index, skip_sample):
    save_data({
        'user_id': st.session_state.user_id,
        'index': st.session_state.current_index,
        **(st.session_state.data.iloc[index][COLS_TO_SAVE].to_dict() if index >= 0 else {}),
        **{k: st.session_state[k + str(index)] for k in st.session_state.data_inputs_keys},
        'skip': skip_sample
    })

# st.set_page_config(layout='wide')
# Title of the app
st.title("Moderator Intervention Prediction")


st.markdown(
    """<style>
div[data-testid="stMarkdownContainer"] > p {
    font-size: 1rem;
}
    section.main > div {max-width:60rem}
    </style>
    """, unsafe_allow_html=True)


def add_annotation_guidelines():
    st.write(f"username is {st.session_state.user_id}")
    st.markdown(
        "<details open><summary><b>Annotation Guidelines</b></summary>" + guidelines_text + "</details><br>"
        , unsafe_allow_html=True)


if 'unacceptable_response' in st.session_state and st.session_state.unacceptable_response:
    add_annotation_guidelines()
    st.error("You are not eligible for this study. Thank you for your time!" +
             ("" if st.session_state.current_index < 0 else
              #" You will receive a small compensation as explained in the guidelines. "
              "Please email eva-maria.vecchi@ims.uni-stuttgart.de for issues or questions."
             ))
    st.stop()


# Load the data to annotate
if 'data' not in st.session_state:
    st.session_state.data = read_data()

# user id
user_id_from_url = get_param_from_url("user_id")
if user_id_from_url:
    st.session_state.user_id = user_id_from_url

# current index
if 'current_index' not in st.session_state:
    start_index = get_start_index()
    st.session_state.current_index = start_index
    st.session_state.form_displayed = -3

if get_param_from_url('show_extra_fields'):
    fields += url_conditional_fields


def add_validated_submit(fields, message):
    st.session_state.form_displayed = st.session_state.current_index
    if st.form_submit_button("Submit"):
        if all(not x for x in fields):
            st.error(message)
        else:
            navigate(1)


def add_checked_submit():
    check = st.checkbox('I agree', key='consent')
    add_validated_submit([check], "Please agree to give your consent to proceed")

if 'go_to' not in st.session_state:
    st.session_state.go_to = 0
    
if st.session_state.current_index == -3:
    with st.form("data_form"):
        st.markdown(consent_text)
        add_checked_submit()

elif st.session_state.current_index == -2:
    if st.session_state.get('user_id'):
        navigate(1)
    else:
        with st.form("data_form"):
            st.session_state.user_id = st.text_input('User ID', value=user_id_from_url)
            add_validated_submit([st.session_state.user_id], "Please enter a valid user ID")


elif st.session_state.current_index == -1:
    add_annotation_guidelines()
    with st.form("intro_form"):
        show_fields(intro_fields)

elif st.session_state.current_index < len(st.session_state.data):
    add_annotation_guidelines()
    with st.form("data_form"+str(st.session_state.current_index)):
        show_fields(fields)

elif st.session_state.current_index == len(st.session_state.data):
    with st.form("intro_form"):
        show_fields(end_fields)
        
else:
    st.write(f"Thank you for taking part in this study!")

# Navigation buttons
if st.session_state.current_index > 0:
        if st.button("Previous"):
            navigate(-1)

if 0 <= st.session_state.current_index < len(st.session_state.data):
    st.write(f"Page {st.session_state.current_index + 1} out of {len(st.session_state.data)}")


def navigate_to_index():
    try:
        go_to_index = int(st.session_state.go_to)-1
        farthest_index = get_start_index()
        # Check if the index is within the valid range
        if 0 <= go_to_index < len(st.session_state.data):
            if go_to_index <= farthest_index:
                st.session_state.current_index = go_to_index
                st.experimental_rerun()
            else: 
                st.info(f"You have not annotated up to instance #{int(st.session_state.go_to)} yet. \nYour last annotated instance was #{farthest_index+1}.")
        else:
            st.info(f"{int(st.session_state.go_to)} is not in the range of data.")
    except ValueError:
        st.error("The page number must be an integer.")

col1, col2, col3 = st.columns([2, 2, 2])
with col2:
    with st.form(key="nav_form"):
        st.number_input("Go to Page: ", key="go_to", format="%.0f")
        if st.form_submit_button("Go"):
            navigate_to_index()

st.markdown(
    """<style>
    div[data-testid="InputInstructions"] {
        visibility: hidden;
    }
    </style>""", unsafe_allow_html=True
)