File size: 7,265 Bytes
99fd41f
818f654
 
cf1362c
818f654
cf1362c
818f654
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf1362c
 
818f654
cf1362c
e113c95
 
 
 
 
818f654
e113c95
 
cf1362c
818f654
e113c95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
818f654
99fd41f
818f654
 
e113c95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
818f654
 
cf1362c
 
818f654
 
 
 
cf1362c
 
e113c95
818f654
cf1362c
e113c95
cf1362c
e113c95
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
import os
import streamlit as st
import yaml
import logging
import pandas as pd
from cryptography.fernet import Fernet, InvalidToken
from dotenv import load_dotenv
from io import StringIO

import modeling

def df_to_csv(df):
    csv = StringIO()
    df.to_csv(csv, index=True)
    csv.seek(0)
    csv_data = csv.getvalue()
    return(csv_data)

def dict_to_yaml(data):
    return yaml.dump(data, default_flow_style=False)

def yaml_to_dict(yaml_str):
    return yaml.safe_load(yaml_str)

def initialize():

    logging.basicConfig(level=logging.INFO)
    load_dotenv()

    st.session_state.setdefault('config', None)
    
    st.session_state.setdefault('encryption_key', None)
    st.session_state.setdefault('is_authenticated', False)
    
    st.session_state.setdefault('db', None)

    st.session_state.setdefault('search_query', None)
    st.session_state.setdefault('search_results', pd.DataFrame())

    if st.session_state['config'] is None:
        with open('config.yaml', 'r') as stream:
            st.session_state['config'] = yaml.safe_load(stream)

def show_authentication():

    with st.container(height=400, border=None, key=None):

        with open('tos.md', 'r', encoding='utf-8') as f:
            tos_content = f.read()
        st.write(tos_content)

    checkbox1 = "I agree to use this application **solely for non-commercial research purposes**. Any other usage is **strictly prohibited**!"
    checkbox2 = "I have **read**, **understood**, and **agree** to be bound by the Terms of Service and Privacy Policy."


    if st.checkbox(label=checkbox1) & st.checkbox(label=checkbox2):

        with st.form("authentication_form", border=False):
            st.markdown("""
                ## Authentication
                This app is a research preview and requires authentication.
                All data is encrypted. Please use your 32-byte encryption key to proceed!
            """)

            st.text_input(
                label="๐Ÿ”‘ Encryption key",
                value="",
                max_chars=None,
                key='encryption_key',
                placeholder="A URL-safe base64-encoded 32-byte key"
            )

            submitted = st.form_submit_button(
                label="Authenticate",
                type="primary",
                use_container_width=True
            )

            if submitted:
                try:
                    modeling.load_db()
                    st.rerun()
                except InvalidToken:
                    error = f"Error: The encryption key you have entered is invalid!"
                    st.error(body=error, icon="๐Ÿ”‘")
                    logging.error(error)
                    st.session_state['is_authenticated'] = False
                    return
                except ValueError as error:
                    st.error(body=error, icon="๐Ÿ”‘")
                    logging.error(error)
                    st.session_state['is_authenticated'] = False
                    return
    # with placeholder:

    #     with st.container():

    #         with st.container(height=200, border=None, key=None):

    #             with open('tos.md', 'r', encoding='utf-8') as f:
    #                 tos_content = f.read()
    #             st.write(tos_content)

    #         checkbox1 = "I agree to use this application **solely for non-commercial research purposes**. Any other usage is **strictly prohibited**!"
    #         checkbox2 = "I have **read**, **understood**, and **agree** to be bound by the Terms of Service and Privacy Policy."


    #         if st.checkbox(label=checkbox1) & st.checkbox(label=checkbox2):
    #             with st.form("authentication_form"):

    #                 st.markdown("""
    #                     ## Authentication
    #                     This app is a research preview and requires authentication.
    #                     All data is encrypted. Please use your 32-byte encryption key to proceed!
    #                 """)



def main():

    with st.container():
        st.divider()
        st.markdown("""
            ## Try it yourself!
            Define a scale by entering individual items in YAML format.
            After form submission, a vector representation for the scale is calculated using the selected encoder model.
            Cosine similarities between this vector and the representations of existing scales are then computed.
            The resulting table outputs measures with high semantic overlap.
        """)

        with st.container():
            if 'input_items' not in st.session_state:
                st.session_state['input_items'] = dict_to_yaml(st.session_state['config']['input_items'])

            with st.form("submission_form"):
                st.text_area(
                    label="Search for similar measures by entering items that constitute the scale (YAML-Formatted):",
                    height=175,
                    key='input_items'
                )


                submitted = st.form_submit_button(
                    label="Search Synth-Net",
                    type="primary",
                    use_container_width=True
                )

                if submitted:

                    try:
                        st.session_state['search_query'] = yaml_to_dict(st.session_state['input_items'])
                    except yaml.YAMLError as e:
                        st.error(f"Yikes, you better get your YAML straight! Check https://yaml.org/ for help! \n {e}")
                        return

                    if not st.session_state.get('model'):
                        modeling.load_model()

                    modeling.search()

                with st.container():
                    if not st.session_state['search_results'].empty:
                        with st.spinner('Rendering search results...'):
                            df = st.session_state['search_results'].style.format({
                                'Match': '{:.2f}'.format,
                                'Scale': str.capitalize,
                                'Instrument': str.capitalize,
                            })
                            st.dataframe(df, use_container_width=True, hide_index=True)

if __name__ == '__main__':
    st.set_page_config(page_title='Synth-Net')
    st.markdown("# The Synthetic Nomological Net")
    st.markdown("""
        Psychological science is experiencing rapid growth in constructs and measures, partly due to refinement and new research areas,
        but also due to excessive proliferation. This proliferation, driven by academic incentives for novelty, may lead to redundant
        constructs with different names (jangle fallacy) and seemingly similar constructs with little content overlap (jingle fallacy).

        This web application uses state-of-the-art models and methods in natural language processing to search for semantic overlap in measures.
        It analyzes textual data from over 21,000 scales (containing more than 330,000 items) in an effort to reduce redundancies in measures used in the behavioral sciences.
    """, unsafe_allow_html=True)

    initialize()

    if st.session_state['is_authenticated']:
        main()
    else:
        show_authentication()