pvqsub24 commited on
Commit
7c639f7
·
1 Parent(s): 97553ab

Initialise Moral Values App

Browse files
Files changed (2) hide show
  1. app.py +198 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from transformers import pipeline
4
+ import torch
5
+ from transformers import AutoModel, AutoTokenizer
6
+ from torch.nn import Softmax
7
+ import torch
8
+ import torch.nn as nn
9
+ from huggingface_hub import PyTorchModelHubMixin
10
+
11
+
12
+ bert_model = AutoModel.from_pretrained("bert-base-uncased")
13
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
14
+
15
+ class MyModel(
16
+ nn.Module,
17
+ PyTorchModelHubMixin,
18
+ # optionally, you can add metadata which gets pushed to the model card
19
+ repo_url="your-repo-url",
20
+ pipeline_tag="text-classification",
21
+ license="mit",
22
+ ):
23
+ def __init__(self, bert_model, moral_label=2):
24
+
25
+ super(MyModel, self).__init__()
26
+ self.bert = bert_model
27
+ bert_dim = 768
28
+ self.invariant_trans = nn.Linear(768, 768)
29
+ self.moral_classification = nn.Sequential(nn.Linear(768,768),
30
+ nn.ReLU(),
31
+ nn.Linear(768, moral_label))
32
+
33
+ def forward(self, input_ids, token_type_ids, attention_mask):
34
+ pooled_output = self.bert(input_ids,
35
+ token_type_ids = token_type_ids,
36
+ attention_mask = attention_mask).last_hidden_state[:,0,:]
37
+
38
+
39
+ pooled_output = self.invariant_trans(pooled_output)
40
+
41
+
42
+ logits = self.moral_classification(pooled_output)
43
+
44
+ return logits
45
+
46
+
47
+ def preprocessing(input_text, tokenizer):
48
+ '''
49
+ Returns with the following fields:
50
+ - input_ids: list of token ids
51
+ - token_type_ids: list of token type ids
52
+ - attention_mask: list of indices (0,1) specifying which tokens should considered by the model (return_attention_mask = True).
53
+ '''
54
+ return tokenizer(
55
+ input_text,
56
+ add_special_tokens = True,
57
+ max_length = 150,
58
+ padding = 'max_length',
59
+ return_attention_mask = True,
60
+ return_token_type_ids = True, # Add this line
61
+ return_tensors = 'pt',
62
+ truncation=True
63
+ )
64
+ # return tokenizer.encode_plus(
65
+ # input_text,
66
+ # add_special_tokens = True,
67
+ # max_length = 150,
68
+ # padding = 'max_length',
69
+ # return_attention_mask = True,
70
+ # return_token_type_ids = True, # Add this line
71
+ # return_tensors = 'pt',
72
+ # truncation=True
73
+ # )
74
+
75
+ # initialising the Softmax function
76
+ soft = Softmax()
77
+
78
+ # Function to load models from Hugging Face Hub
79
+ @st.cache_resource
80
+ def get_model_score(sentence, mft):
81
+ # repo_name = f"vjosap/moralBERT-predict-{mft}-in-text"
82
+ repo_name = f"vjosap/moralBERT-predict-{mft}-in-{model_type}"
83
+
84
+ # loading the model
85
+ model = MyModel.from_pretrained(repo_name, bert_model=bert_model)
86
+
87
+ # preprocessing the text
88
+ encodeds = preprocessing(sentence, tokenizer)
89
+
90
+ # predicting the mft score
91
+ output = model(**encodeds)
92
+ score = soft(output)
93
+
94
+ # extracting and return the second value from the tensor
95
+ #mft_value = score[0, 1].item()
96
+ mft_value = score[:, 1].tolist()
97
+
98
+ return mft_value
99
+
100
+ @st.cache_resource
101
+ def load_model(model_name):
102
+ return pipeline("text-classification", model=model_name, return_all_scores=True)
103
+
104
+
105
+ page_element="""
106
+ <style>
107
+ [data-testid="stAppViewContainer"]{
108
+ background-image: url("https://w7.pngwing.com/pngs/980/181/png-transparent-flat-white-background-abstract-flat-white-thumbnail.png");
109
+ background-size: cover;
110
+ }
111
+ [data-testid="stHeader"]{
112
+ background-color: rgba(0,0,0,0);
113
+ }
114
+ [data-testid="stToolbar"]{
115
+ right: 2rem;
116
+ background-image: url("https://img.freepik.com/premium-vector/burger-icon-isolated-illustration_92753-2926.jpg?w=2000");
117
+ background-size: cover;
118
+ }
119
+ </style>
120
+ """
121
+ st.markdown(page_element, unsafe_allow_html=True)
122
+
123
+ # File upload section
124
+ st.title("Moral Values Detection App")
125
+ st.markdown("Authors: [Vjosa Preniqi](https://scholar.google.com/citations?user=CLZ3LL4AAAAJ&hl=en) and [Iacopo Ghinassi](https://scholar.google.com/citations?user=ANXW5EAAAAAJ&hl=en).")
126
+ st.header("Introduction", divider = "red")
127
+ st.markdown("""This app implements the models described in the papers [MoralBERT: A Fine-Tuned Language Model for Capturing Moral Values in Social Discussions](https://dl.acm.org/doi/abs/10.1145/3677525.3678694) and [Automatic Detection of Moral Values in Music Lyrics](https://arxiv.org/abs/2407.18787). With this app, you can automatically predict and label text or music lyrics with 10 moral categories.To use it, upload a CSV file with a single column named "text" (for regular text) or "lyrics" (for music lyrics). Each row should have the text or lyric you want to analyse. Keep in mind, the process may take up to 10 seconds per entry, and the models work best with social media content and music lyrics. Once the analysis is done, the app will show a table with the predicted probabilities for each moral value. You can download this table using the provided button. Note that some moral values might have consistently low probabilities. If that's the case, you may need to use a lower threshold to identify them—check the original papers for more details.""")
128
+ model_type = st.radio("Choose the type of text for prediction", ('text', 'lyrics'))
129
+
130
+ # Warning if model type is not selected before file upload
131
+ if not model_type:
132
+ st.warning("Please pick the text type for prediction first.")
133
+
134
+ # File upload section
135
+ st.write(f"Upload a CSV file with a column named 'text' or 'lyrics' for based on the model type you chose.")
136
+
137
+ uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
138
+
139
+
140
+ if uploaded_file is not None:
141
+ # Read CSV
142
+ df = pd.read_csv(uploaded_file)
143
+
144
+ # Validation: Check if the correct column exists based on the selected model type
145
+ expected_column = 'lyrics' if model_type == 'lyrics' else 'text'
146
+
147
+ if expected_column not in df.columns:
148
+ st.error(f"Please upload a CSV file with a '{expected_column}' column since you selected '{model_type}' for prediction.")
149
+ else:
150
+ textual_content = df[expected_column].tolist()
151
+
152
+ # List of moral foundation models
153
+ models = ["care", "harm", "fairness", "cheating", "loyalty", "betrayal", "authority", "subversion", "purity", "degradation"]
154
+
155
+ # Initialize the dataframe to store results
156
+ result_df = pd.DataFrame(textual_content, columns=[expected_column])
157
+
158
+ batch_size = 64
159
+ # Perform predictions using each model
160
+ for model_name in models:
161
+ st.write(f"Processing with model: {model_name}")
162
+ probabilities = []
163
+
164
+ # Process in batches
165
+
166
+ for idx in range(len(textual_content)//batch_size):
167
+ preds = get_model_score(textual_content[idx*batch_size:(idx+1)*batch_size], model_name)
168
+ probabilities.extend(preds)
169
+
170
+ # if len(textual_content)%batch_size:
171
+ # preds = get_model_score(textual_content[(idx+1)*batch_size:], model_name)
172
+ # probabilities.extend(preds)
173
+
174
+ # Handle the remainder if the total number of items isn't a multiple of batch_size
175
+ remainder_start = (len(textual_content) // batch_size) * batch_size
176
+ if len(textual_content) % batch_size:
177
+ preds = get_model_score(textual_content[remainder_start:], model_name)
178
+ probabilities.extend(preds)
179
+
180
+ # Add the results to the dataframe
181
+ result_df[f'{model_name}'] = probabilities
182
+
183
+ # Display the dataframe
184
+ st.dataframe(result_df)
185
+
186
+ # Button to download the dataframe as CSV
187
+ @st.cache_data
188
+ def convert_df(df):
189
+ return df.to_csv(index=False).encode('utf-8')
190
+
191
+ csv = convert_df(result_df)
192
+
193
+ st.download_button(
194
+ label="Download Results as CSV",
195
+ data=csv,
196
+ file_name='predictions.csv',
197
+ mime='text/csv',
198
+ )
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ streamlit
2
+ transformers
3
+ pandas
4
+ torch