Spaces:
Runtime error
Runtime error
Minor text correction
Browse files
app.py
CHANGED
@@ -1,314 +1,314 @@
|
|
1 |
-
import json
|
2 |
-
import streamlit as st
|
3 |
-
import pandas as pd
|
4 |
-
import seaborn as sns
|
5 |
-
import plotly.graph_objects as go
|
6 |
-
import plotly.express as px
|
7 |
-
from st_social_media_links import SocialMediaIcons
|
8 |
-
|
9 |
-
|
10 |
-
RESULTS_COLUMN_NAME = "Results"
|
11 |
-
AVERAGE_COLUMN_NAME = "Average"
|
12 |
-
SENTIMENT_COLUMN_NAME = "Sentiment"
|
13 |
-
UNDERSTANDING_COLUMN_NAME = "Language understanding"
|
14 |
-
PHRASEOLOGY_COLUMN_NAME = "Phraseology"
|
15 |
-
|
16 |
-
# Function to load data from JSON file
|
17 |
-
@st.cache_data
|
18 |
-
def load_data(file_path):
|
19 |
-
with open(file_path, 'r', encoding='utf-8') as file:
|
20 |
-
data = json.load(file)
|
21 |
-
return pd.DataFrame(data)
|
22 |
-
|
23 |
-
# Function to style the DataFrame
|
24 |
-
@st.cache_data
|
25 |
-
def style_dataframe(df: pd.DataFrame):
|
26 |
-
df[RESULTS_COLUMN_NAME] = df.apply(lambda row: [row[SENTIMENT_COLUMN_NAME], row[UNDERSTANDING_COLUMN_NAME], row[PHRASEOLOGY_COLUMN_NAME]], axis=1)
|
27 |
-
# Insert the new column after the 'Average' column
|
28 |
-
cols = list(df.columns)
|
29 |
-
cols.insert(cols.index(AVERAGE_COLUMN_NAME) + 1, cols.pop(cols.index(RESULTS_COLUMN_NAME)))
|
30 |
-
df = df[cols]
|
31 |
-
# Create a color ramp using Seaborn
|
32 |
-
return df
|
33 |
-
|
34 |
-
def styler(df: pd.DataFrame):
|
35 |
-
palette = sns.color_palette("RdYlGn", as_cmap=True)
|
36 |
-
# Apply reverse color gradient to the "Params" column
|
37 |
-
params_palette = sns.color_palette("RdYlGn_r", as_cmap=True) # Reversed RdYlGn palette
|
38 |
-
styled_df = df.style.background_gradient(cmap=palette, subset=[AVERAGE_COLUMN_NAME, SENTIMENT_COLUMN_NAME, PHRASEOLOGY_COLUMN_NAME, UNDERSTANDING_COLUMN_NAME]
|
39 |
-
).background_gradient(cmap=params_palette, subset=["Params"]
|
40 |
-
).set_properties(**{'text-align': 'center'}, subset=[AVERAGE_COLUMN_NAME, SENTIMENT_COLUMN_NAME, PHRASEOLOGY_COLUMN_NAME, UNDERSTANDING_COLUMN_NAME]
|
41 |
-
).format("{:.2f}".center(10), subset=[AVERAGE_COLUMN_NAME, SENTIMENT_COLUMN_NAME, PHRASEOLOGY_COLUMN_NAME, UNDERSTANDING_COLUMN_NAME]
|
42 |
-
).format("{:.1f}".center(10), subset=["Params"])
|
43 |
-
return styled_df
|
44 |
-
|
45 |
-
|
46 |
-
### Streamlit app
|
47 |
-
st.set_page_config(layout="wide")
|
48 |
-
|
49 |
-
st.markdown("""
|
50 |
-
<style>
|
51 |
-
.block-container {
|
52 |
-
padding-top: 0%;
|
53 |
-
padding-bottom: 0%;
|
54 |
-
padding-left: 3%;
|
55 |
-
padding-right: 3%;
|
56 |
-
scrollbar-width: thin;
|
57 |
-
}
|
58 |
-
</style>
|
59 |
-
""", unsafe_allow_html=True)
|
60 |
-
|
61 |
-
### Prepare layout
|
62 |
-
|
63 |
-
st.markdown("""
|
64 |
-
<style>
|
65 |
-
.center {
|
66 |
-
display: block;
|
67 |
-
margin-left: auto;
|
68 |
-
margin-right: auto;
|
69 |
-
width: 50%;
|
70 |
-
}
|
71 |
-
.center-text {
|
72 |
-
text-align: center;
|
73 |
-
}
|
74 |
-
|
75 |
-
a:link {color:#FDA428;} /* unvisited link */
|
76 |
-
a:hover {color:#FDA428;} /* Mouse over link */
|
77 |
-
a:visited {color:#FDA428;} /* visited link */
|
78 |
-
a:active {color:#FDA428;} /* selected link */
|
79 |
-
|
80 |
-
</style>
|
81 |
-
""", unsafe_allow_html=True)
|
82 |
-
|
83 |
-
# --- Colors info ---
|
84 |
-
# Primary Color: #FDA428
|
85 |
-
# Secondary Color: #A85E00
|
86 |
-
# Grey Color: #7B7B7B
|
87 |
-
# Background Color: #1C1C1C
|
88 |
-
# {'LOW': '#7B7B7B', 'MEDIUM': '#A85E00', 'HIGH': '#FDA428'}
|
89 |
-
# ----------------------------------------------------------
|
90 |
-
st.markdown("""<br>""", unsafe_allow_html=True)
|
91 |
-
|
92 |
-
### Row: 1 --> Title + links to SpeakLeash.org website / GitHub / X (Twitter)
|
93 |
-
social_media_links = [
|
94 |
-
"https://discord.com/invite/ZJwCMrxwT7",
|
95 |
-
"https://github.com/speakleash",
|
96 |
-
"https://x.com/Speak_Leash",
|
97 |
-
"https://www.linkedin.com/company/speakleash/",
|
98 |
-
"https://www.facebook.com/Speakleash/"
|
99 |
-
]
|
100 |
-
|
101 |
-
light_orange = "#FDA428"
|
102 |
-
dark_orange = "#A85E00"
|
103 |
-
white_color = "#FFFFFF"
|
104 |
-
black_color = "#000000"
|
105 |
-
links_color = light_orange
|
106 |
-
|
107 |
-
social_media_links_colors = [
|
108 |
-
links_color,
|
109 |
-
links_color,
|
110 |
-
links_color,
|
111 |
-
links_color,
|
112 |
-
links_color
|
113 |
-
]
|
114 |
-
|
115 |
-
social_media_icons = SocialMediaIcons(social_media_links, social_media_links_colors)
|
116 |
-
social_media_icons.render(justify_content='right')
|
117 |
-
|
118 |
-
st.markdown("""
|
119 |
-
<hr style="margin: 0.5em 0;">
|
120 |
-
""", unsafe_allow_html=True)
|
121 |
-
|
122 |
-
st.markdown("""
|
123 |
-
<img src="https://speakleash.org/wp-content/uploads/2023/09/SpeakLeash_logo.svg" alt="SpeakLeash Logo">
|
124 |
-
""", unsafe_allow_html=True)
|
125 |
-
|
126 |
-
# Add logo, title, and subheader in a flexible container with equal spacing
|
127 |
-
st.markdown("""
|
128 |
-
<div class="header-container">
|
129 |
-
<br><br>
|
130 |
-
<div class="title-container">
|
131 |
-
<h1 style='color: #FDA428; margin-top: -1rem; font-size: 3.1em;'>CPTUB - Complex Polish Text Understanging Benchmark</h1>
|
132 |
-
<h3 style="margin-top: 0;">Understanding of Polish text, sentiment and phraseological compounds</h2>
|
133 |
-
</div>
|
134 |
-
</div>
|
135 |
-
""", unsafe_allow_html=True)
|
136 |
-
|
137 |
-
# Create tabs
|
138 |
-
tab1, tab2 = st.tabs([RESULTS_COLUMN_NAME, "Description"])
|
139 |
-
|
140 |
-
with tab1:
|
141 |
-
st.write("This benchmark evaluates the ability of language models to correctly interpret Polish texts with complex implicatures, such as sarcasm and idiomatic expressions. Models are assessed on sentiment analysis, understanding of true intentions, and identification of idiomatic phrases.")
|
142 |
-
|
143 |
-
# Prepare data
|
144 |
-
data = load_data('data.json')
|
145 |
-
|
146 |
-
data['Params'] = data['Params'].str.replace('B', '').astype(float)
|
147 |
-
data = data.sort_values(by=AVERAGE_COLUMN_NAME, ascending=False)
|
148 |
-
|
149 |
-
# Closing filters in a expander
|
150 |
-
with st.expander("Filtering benchmark data", icon='🔍'):
|
151 |
-
# Filtering data, e.g. slider for params, average score, etc.
|
152 |
-
col_filter_params, col_filter_average, col_filter_sentiment, col_filter_understanding, col_filter_phraseology = st.columns(5, gap='medium')
|
153 |
-
|
154 |
-
with col_filter_params:
|
155 |
-
params_slider = st.slider("Models Size [B]", min_value=0.0, max_value=float(data['Params'].max()), value=(0.0, float(data['Params'].max())), step=0.1, format="%.1f")
|
156 |
-
data = data[(data['Params'] >= params_slider[0]) & (data['Params'] <= params_slider[1])]
|
157 |
-
|
158 |
-
with col_filter_average:
|
159 |
-
average_slider = st.slider("Average score", step=0.1, min_value=0.0, max_value=5.0, value=(0.0, 5.0))
|
160 |
-
data = data[(data[AVERAGE_COLUMN_NAME] >= average_slider[0]) & (data[AVERAGE_COLUMN_NAME] <= average_slider[1])]
|
161 |
-
|
162 |
-
with col_filter_sentiment:
|
163 |
-
sentiment_slider = st.slider("Sentiment score", step=0.1, min_value=0.0, max_value=5.0, value=(0.0, 5.0))
|
164 |
-
data = data[(data[SENTIMENT_COLUMN_NAME] >= sentiment_slider[0]) & (data[SENTIMENT_COLUMN_NAME] <= sentiment_slider[1])]
|
165 |
-
|
166 |
-
with col_filter_understanding:
|
167 |
-
understanding_slider = st.slider("Understanding score", step=0.1, min_value=0.0, max_value=5.0, value=(0.0, 5.0))
|
168 |
-
data = data[(data[UNDERSTANDING_COLUMN_NAME] >= understanding_slider[0]) & (data[UNDERSTANDING_COLUMN_NAME] <= understanding_slider[1])]
|
169 |
-
|
170 |
-
with col_filter_phraseology:
|
171 |
-
phraseology_slider = st.slider("Phraseology score", step=0.1, min_value=0.0, max_value=5.0, value=(0.0, 5.0))
|
172 |
-
data = data[(data[PHRASEOLOGY_COLUMN_NAME] >= phraseology_slider[0]) & (data[PHRASEOLOGY_COLUMN_NAME] <= phraseology_slider[1])]
|
173 |
-
|
174 |
-
# Extract unique provider names from the "Model" column
|
175 |
-
providers = data["Model"].apply(lambda x: x.split('/')[0].lower()).unique()
|
176 |
-
selected_providers = st.multiselect("Model providers", providers, default=providers)
|
177 |
-
# Filter data based on selected providers
|
178 |
-
data = data[data["Model"].apply(lambda x: x.split('/')[0]).isin(selected_providers)]
|
179 |
-
|
180 |
-
### Display data
|
181 |
-
styled_df_show = style_dataframe(data)
|
182 |
-
styled_df_show = styler(styled_df_show)
|
183 |
-
|
184 |
-
st.data_editor(styled_df_show, column_config={
|
185 |
-
"Model": st.column_config.TextColumn("Model", help="Model name", width="large"),
|
186 |
-
"Params": st.column_config.NumberColumn("Params [B]"),
|
187 |
-
AVERAGE_COLUMN_NAME: st.column_config.NumberColumn(AVERAGE_COLUMN_NAME),
|
188 |
-
RESULTS_COLUMN_NAME: st.column_config.BarChartColumn(
|
189 |
-
"Bar chart of results", help="Summary of the results of each task",
|
190 |
-
y_min=0,y_max=5,),
|
191 |
-
SENTIMENT_COLUMN_NAME: st.column_config.NumberColumn(SENTIMENT_COLUMN_NAME, help='Ability to analyze sentiment'),
|
192 |
-
UNDERSTANDING_COLUMN_NAME: st.column_config.NumberColumn(UNDERSTANDING_COLUMN_NAME, help='Ability to understand language'),
|
193 |
-
PHRASEOLOGY_COLUMN_NAME: st.column_config.NumberColumn(PHRASEOLOGY_COLUMN_NAME, help='Ability to understand phraseological compounds'),
|
194 |
-
}, hide_index=True, disabled=True, height=500)
|
195 |
-
|
196 |
-
# Add selection for models and create a bar chart for selected models using the AVERAGE_COLUMN_NAME, SENTIMENT_COLUMN_NAME, PHRASEOLOGY_COLUMN_NAME, UNDERSTANDING_COLUMN_NAME
|
197 |
-
# Add default selection of 3 best models from AVERAGE_COLUMN_NAME and 1 best model with "Bielik" in Model column
|
198 |
-
default_models = list(data.sort_values(AVERAGE_COLUMN_NAME, ascending=False)['Model'].head(3))
|
199 |
-
bielik_model = data[data['Model'].str.contains('Bielik')].sort_values(AVERAGE_COLUMN_NAME, ascending=False)['Model'].iloc[0]
|
200 |
-
if bielik_model not in default_models:
|
201 |
-
default_models.append(bielik_model)
|
202 |
-
selected_models = st.multiselect("Select models to compare", data["Model"].unique(), default=default_models)
|
203 |
-
selected_data = data[data["Model"].isin(selected_models)]
|
204 |
-
categories = [AVERAGE_COLUMN_NAME, SENTIMENT_COLUMN_NAME, PHRASEOLOGY_COLUMN_NAME, UNDERSTANDING_COLUMN_NAME]
|
205 |
-
|
206 |
-
if selected_models:
|
207 |
-
# Kolorki do wyboru:
|
208 |
-
# colors = px.colors.sample_colorscale("viridis", len(selected_models)+1)
|
209 |
-
colors = px.colors.qualitative.G10[:len(selected_models)]
|
210 |
-
|
211 |
-
fig_bars = go.Figure()
|
212 |
-
for model, color in zip(selected_models, colors):
|
213 |
-
values = selected_data[selected_data['Model'] == model][categories].values.flatten().tolist()
|
214 |
-
fig_bars.add_trace(go.Bar(
|
215 |
-
x=categories,
|
216 |
-
y=values,
|
217 |
-
name=model,
|
218 |
-
marker_color=color
|
219 |
-
))
|
220 |
-
|
221 |
-
# Update layout to use a custom color scale
|
222 |
-
fig_bars.update_layout(
|
223 |
-
showlegend=True,
|
224 |
-
legend=dict(orientation="h", yanchor="top", y=-0.3, xanchor="center", x=0.5),
|
225 |
-
title="Comparison of Selected Models",
|
226 |
-
yaxis_title="Score",
|
227 |
-
template="plotly_dark"
|
228 |
-
)
|
229 |
-
fig_bars.update_yaxes(range=[0, 5.1])
|
230 |
-
st.plotly_chart(fig_bars)
|
231 |
-
|
232 |
-
|
233 |
-
### Zakładka 2 --> Opis
|
234 |
-
with tab2:
|
235 |
-
st.markdown("""
|
236 |
-
### <span style='text-decoration: #FDA428 wavy underline;'>**Cause of Creation**</span>
|
237 |
-
1. **Need**: Models face significant challenges when dealing with understanding complex, context-reliant texts that involve meanings implied beyond the literal content of a statement. Such cases include sarcasm, implicatures, and phraseological compounds.
|
238 |
-
|
239 |
-
Traditional sentiment classifiers typically rely on word-based features (e.g., identifying positive or negative words) to assess sentiment. However, with sarcasm, the literal meaning of words often contradicts the intended sentiment, making it difficult for models to accurately gauge tone. Sarcasm's context-dependence further complicates matters, as these classifiers typically lack the ability to grasp nuanced cues in context, especially when sarcasm is subtle.
|
240 |
-
Similarly, classifiers struggle with implicatures, where the underlying intent is implied rather than explicitly stated. Here, models fail to capture the full sentiment because they rely heavily on surface-level words, missing the non-literal meaning that often drives the sentiment.
|
241 |
-
Phraseological compounds add another layer of difficulty. These are fixed or semi-fixed expressions whose meanings cannot be directly inferred from the individual words. Language models, trained on word-level patterns, often misinterpret these expressions because they fail to recognize the idiomatic or non-literal meaning, leading to inaccurate sentiment analysis.
|
242 |
-
In addition to sentiment analysis, we decided to include the understanding of more complex texts in the benchmark, which was measured by the ability to uncover the intended meaning.
|
243 |
-
|
244 |
-
### <span style='text-decoration: #FDA428 wavy underline;'>**Dataset Information**</span>
|
245 |
-
The dataset contains 200 examples, all written in Polish. Each example consists of the following:
|
246 |
-
- **Main Text**: This is a statement (often an opinion) on any topic that includes a certain type of implicature, often several simultaneously, such as sarcasm
|
247 |
-
- **Reference Sentiment**: The sentiment associated with the main text. We use three categories: negative, neutral, and positive. Ambiguous examples were labeled as "neutral" to exclude them from sentiment classification testing.
|
248 |
-
- **Reference phraseological compounds**: A list of phraseological compounds found in the main text.
|
249 |
-
- **Reference Explanation**: An explanation of the underlying intentions that the author of the main text might have had.
|
250 |
-
|
251 |
-
### <span style='text-decoration: #FDA428 wavy underline;'>**Evaluation Procedure**</span>
|
252 |
-
We distinguish between two models in the evaluation process:
|
253 |
-
- **Evaluated Model**: The model that performs specific tasks, is then assessed based on its performance, and added to a ranking.
|
254 |
-
- **Judge Metamodel**: One of the currently strongest, most versatile LLMs.
|
255 |
-
|
256 |
-
### <span style='text-decoration: #FDA428 wavy underline;'>**GENERATING RESPONSES FROM THE EVALUATED MODEL**</span>
|
257 |
-
1. For each text in the dataset, the evaluated model was required to list the following in three points:
|
258 |
-
- The sentiment (only positive/negative).
|
259 |
-
- The underlying intentions of the author of the text.
|
260 |
-
- All phraseological compounds present in the text along with their meanings in the given context.
|
261 |
-
2. No system prompt is used. The prompt provided to the evaluated model is written in Polish, as we are testing the models in this language. It contains:
|
262 |
-
- **User Prompt**: 3 elements, each consisting of a header written in capital letters and content enclosed in triple quotes:
|
263 |
-
- Information about the role of a careful linguist with extensive experience.
|
264 |
-
- The instruction to perform the three previously described tasks.
|
265 |
-
- The first example of a text that could be included in the dataset.
|
266 |
-
- **Assistant Prompt**: A human-written example answer for the first example text.
|
267 |
-
- **User Prompt**: A second example of a text that could be included in the dataset.
|
268 |
-
- **Assistant Prompt**: A human-written example answer for the second example text.
|
269 |
-
- **User Prompt**: The target text, based on which the evaluated model will be assessed.
|
270 |
-
3. The decision to split the examples into user prompts and assistant prompts was made due to the better results achieved by the vast majority of models. The two examples were selected based on diversity: one has a negative sentiment and several phraseological compounds, while the other is positive and lacks phraseological compounds.
|
271 |
-
|
272 |
-
### <span style='text-decoration: #FDA428 wavy underline;'>**GENERATING METAMODEL EVALUATIONS**</span>
|
273 |
-
1. The purpose of the metamodel is to return the following evaluations:
|
274 |
-
- **Understanding of the Text**: A comparison of the evaluated model's response description to the reference explanation.
|
275 |
-
- **Sentiment Analysis**: An optional evaluation, only if the reference sentiment is "positive" or "negative." We made this decision to exclude texts that people might interpret ambiguously.
|
276 |
-
- **phraseological compounds**: The model is penalized for phrases not included in the reference phraseological compounds. In cases where there are no phraseological compounds, the highest score is awarded only if the model indicates the absence of such expressions — one point is deducted for each excess phrase until the score reaches zero.
|
277 |
-
2. Each evaluation is provided in JSON format. Example of a full response from the metamodel:
|
278 |
-
```json
|
279 |
-
{"WYDŹWIĘK": "5"}
|
280 |
-
{"OCENA": "4"}
|
281 |
-
{"ZWIĄZKI": "3"}
|
282 |
-
```
|
283 |
-
3. The judge metamodel's prompt structure is similar to that of the evaluated model's prompt. No system prompt is used. The prompt includes:
|
284 |
-
- **User Prompt**: 3 elements, each consisting of a header written in capital letters and content enclosed in triple quotes:
|
285 |
-
- **Role**: A reliable assistant who adheres to the instructions and does not perform any other tasks, nor enters any additional text in the response.
|
286 |
-
- **Task**: According to the description in point 1. The comparison of phraseological compounds has the most guidelines, so we noted that the model should focus on this as it is the most challenging step, and that its work will be evaluated based on this point.
|
287 |
-
- The first example of a potential response from the evaluated model along with the references.
|
288 |
-
- **Assistant Prompt**: An example response containing the evaluations.
|
289 |
-
- **User Prompt**: A second example of a potential response from the evaluated model along with the references.
|
290 |
-
- **Assistant Prompt**: An example response containing the evaluations for the second example.
|
291 |
-
- **User Prompt**: The actual response from the evaluated model and the references on which the metamodel will base its evaluations included in the benchmark.
|
292 |
-
4. Here, the examples were also selected based on diversity. One includes a reference with a positive sentiment, while the other contains no reference sentiment at all (an example labeled as "neutral" in the dataset).
|
293 |
-
5. It is worth explaining why we chose this particular process for evaluating phraseological compounds. Initially, we intended to check only those phrases included in the reference and ignore others in the evaluation. Unfortunately, this procedure favored models that provided many phrases that were not phraseological compounds.
|
294 |
-
Therefore, we decided to penalize models for phrases not included in the reference. We aimed to ensure that models were not penalized for providing phraseological compounds we had not included in the reference. After generating the responses, we collected phrases noted by several models and manually reviewed all references to identify phraseological compounds we might have missed.
|
295 |
-
A similar procedure was applied to sentiment analysis—we listed all examples where several models consistently recorded a different sentiment than the reference and reconsidered whether the examples could be interpreted differently than initially assumed.
|
296 |
-
""", unsafe_allow_html=True)
|
297 |
-
|
298 |
-
|
299 |
-
# Ending :)
|
300 |
-
st.markdown("<hr style='border: 1px solid #A85E00;'>", unsafe_allow_html=True)
|
301 |
-
# st.divider()
|
302 |
-
st.markdown("""
|
303 |
-
### Authors:
|
304 |
-
- [Jan Sowa](https://www.linkedin.com/in/janpiotrsowa) - leadership, writing texts, benchmark code
|
305 |
-
- [Agnieszka Kosiak](https://www.linkedin.com/in/agn-kosiak/) - writing texts
|
306 |
-
- [Magdalena Krawczyk](https://www.linkedin.com/in/magdalena-krawczyk-7810942ab/) - writing texts, labeling
|
307 |
-
- [Remigiusz Kinas](https://www.linkedin.com/in/remigiusz-kinas/) - methodological support
|
308 |
-
- [Krzysztof Wróbel](https://www.linkedin.com/in/wrobelkrzysztof/) - engineering, methodological support
|
309 |
-
- [Szymon Baczyński](https://www.linkedin.com/in/szymon-baczynski/) - front-end / streamlit assistant
|
310 |
-
""")
|
311 |
-
|
312 |
-
st.divider()
|
313 |
-
|
314 |
# Run the app with `streamlit run your_script.py`
|
|
|
1 |
+
import json
|
2 |
+
import streamlit as st
|
3 |
+
import pandas as pd
|
4 |
+
import seaborn as sns
|
5 |
+
import plotly.graph_objects as go
|
6 |
+
import plotly.express as px
|
7 |
+
from st_social_media_links import SocialMediaIcons
|
8 |
+
|
9 |
+
|
10 |
+
RESULTS_COLUMN_NAME = "Results"
|
11 |
+
AVERAGE_COLUMN_NAME = "Average"
|
12 |
+
SENTIMENT_COLUMN_NAME = "Sentiment"
|
13 |
+
UNDERSTANDING_COLUMN_NAME = "Language understanding"
|
14 |
+
PHRASEOLOGY_COLUMN_NAME = "Phraseology"
|
15 |
+
|
16 |
+
# Function to load data from JSON file
|
17 |
+
@st.cache_data
|
18 |
+
def load_data(file_path):
|
19 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
20 |
+
data = json.load(file)
|
21 |
+
return pd.DataFrame(data)
|
22 |
+
|
23 |
+
# Function to style the DataFrame
|
24 |
+
@st.cache_data
|
25 |
+
def style_dataframe(df: pd.DataFrame):
|
26 |
+
df[RESULTS_COLUMN_NAME] = df.apply(lambda row: [row[SENTIMENT_COLUMN_NAME], row[UNDERSTANDING_COLUMN_NAME], row[PHRASEOLOGY_COLUMN_NAME]], axis=1)
|
27 |
+
# Insert the new column after the 'Average' column
|
28 |
+
cols = list(df.columns)
|
29 |
+
cols.insert(cols.index(AVERAGE_COLUMN_NAME) + 1, cols.pop(cols.index(RESULTS_COLUMN_NAME)))
|
30 |
+
df = df[cols]
|
31 |
+
# Create a color ramp using Seaborn
|
32 |
+
return df
|
33 |
+
|
34 |
+
def styler(df: pd.DataFrame):
|
35 |
+
palette = sns.color_palette("RdYlGn", as_cmap=True)
|
36 |
+
# Apply reverse color gradient to the "Params" column
|
37 |
+
params_palette = sns.color_palette("RdYlGn_r", as_cmap=True) # Reversed RdYlGn palette
|
38 |
+
styled_df = df.style.background_gradient(cmap=palette, subset=[AVERAGE_COLUMN_NAME, SENTIMENT_COLUMN_NAME, PHRASEOLOGY_COLUMN_NAME, UNDERSTANDING_COLUMN_NAME]
|
39 |
+
).background_gradient(cmap=params_palette, subset=["Params"]
|
40 |
+
).set_properties(**{'text-align': 'center'}, subset=[AVERAGE_COLUMN_NAME, SENTIMENT_COLUMN_NAME, PHRASEOLOGY_COLUMN_NAME, UNDERSTANDING_COLUMN_NAME]
|
41 |
+
).format("{:.2f}".center(10), subset=[AVERAGE_COLUMN_NAME, SENTIMENT_COLUMN_NAME, PHRASEOLOGY_COLUMN_NAME, UNDERSTANDING_COLUMN_NAME]
|
42 |
+
).format("{:.1f}".center(10), subset=["Params"])
|
43 |
+
return styled_df
|
44 |
+
|
45 |
+
|
46 |
+
### Streamlit app
|
47 |
+
st.set_page_config(layout="wide")
|
48 |
+
|
49 |
+
st.markdown("""
|
50 |
+
<style>
|
51 |
+
.block-container {
|
52 |
+
padding-top: 0%;
|
53 |
+
padding-bottom: 0%;
|
54 |
+
padding-left: 3%;
|
55 |
+
padding-right: 3%;
|
56 |
+
scrollbar-width: thin;
|
57 |
+
}
|
58 |
+
</style>
|
59 |
+
""", unsafe_allow_html=True)
|
60 |
+
|
61 |
+
### Prepare layout
|
62 |
+
|
63 |
+
st.markdown("""
|
64 |
+
<style>
|
65 |
+
.center {
|
66 |
+
display: block;
|
67 |
+
margin-left: auto;
|
68 |
+
margin-right: auto;
|
69 |
+
width: 50%;
|
70 |
+
}
|
71 |
+
.center-text {
|
72 |
+
text-align: center;
|
73 |
+
}
|
74 |
+
|
75 |
+
a:link {color:#FDA428;} /* unvisited link */
|
76 |
+
a:hover {color:#FDA428;} /* Mouse over link */
|
77 |
+
a:visited {color:#FDA428;} /* visited link */
|
78 |
+
a:active {color:#FDA428;} /* selected link */
|
79 |
+
|
80 |
+
</style>
|
81 |
+
""", unsafe_allow_html=True)
|
82 |
+
|
83 |
+
# --- Colors info ---
|
84 |
+
# Primary Color: #FDA428
|
85 |
+
# Secondary Color: #A85E00
|
86 |
+
# Grey Color: #7B7B7B
|
87 |
+
# Background Color: #1C1C1C
|
88 |
+
# {'LOW': '#7B7B7B', 'MEDIUM': '#A85E00', 'HIGH': '#FDA428'}
|
89 |
+
# ----------------------------------------------------------
|
90 |
+
st.markdown("""<br>""", unsafe_allow_html=True)
|
91 |
+
|
92 |
+
### Row: 1 --> Title + links to SpeakLeash.org website / GitHub / X (Twitter)
|
93 |
+
social_media_links = [
|
94 |
+
"https://discord.com/invite/ZJwCMrxwT7",
|
95 |
+
"https://github.com/speakleash",
|
96 |
+
"https://x.com/Speak_Leash",
|
97 |
+
"https://www.linkedin.com/company/speakleash/",
|
98 |
+
"https://www.facebook.com/Speakleash/"
|
99 |
+
]
|
100 |
+
|
101 |
+
light_orange = "#FDA428"
|
102 |
+
dark_orange = "#A85E00"
|
103 |
+
white_color = "#FFFFFF"
|
104 |
+
black_color = "#000000"
|
105 |
+
links_color = light_orange
|
106 |
+
|
107 |
+
social_media_links_colors = [
|
108 |
+
links_color,
|
109 |
+
links_color,
|
110 |
+
links_color,
|
111 |
+
links_color,
|
112 |
+
links_color
|
113 |
+
]
|
114 |
+
|
115 |
+
social_media_icons = SocialMediaIcons(social_media_links, social_media_links_colors)
|
116 |
+
social_media_icons.render(justify_content='right')
|
117 |
+
|
118 |
+
st.markdown("""
|
119 |
+
<hr style="margin: 0.5em 0;">
|
120 |
+
""", unsafe_allow_html=True)
|
121 |
+
|
122 |
+
st.markdown("""
|
123 |
+
<img src="https://speakleash.org/wp-content/uploads/2023/09/SpeakLeash_logo.svg" alt="SpeakLeash Logo">
|
124 |
+
""", unsafe_allow_html=True)
|
125 |
+
|
126 |
+
# Add logo, title, and subheader in a flexible container with equal spacing
|
127 |
+
st.markdown("""
|
128 |
+
<div class="header-container">
|
129 |
+
<br><br>
|
130 |
+
<div class="title-container">
|
131 |
+
<h1 style='color: #FDA428; margin-top: -1rem; font-size: 3.1em;'>CPTUB - Complex Polish Text Understanging Benchmark</h1>
|
132 |
+
<h3 style="margin-top: 0;">Understanding of Polish text, sentiment and phraseological compounds</h2>
|
133 |
+
</div>
|
134 |
+
</div>
|
135 |
+
""", unsafe_allow_html=True)
|
136 |
+
|
137 |
+
# Create tabs
|
138 |
+
tab1, tab2 = st.tabs([RESULTS_COLUMN_NAME, "Description"])
|
139 |
+
|
140 |
+
with tab1:
|
141 |
+
st.write("This benchmark evaluates the ability of language models to correctly interpret Polish texts with complex implicatures, such as sarcasm and idiomatic expressions. Models are assessed on sentiment analysis, understanding of true intentions, and identification of idiomatic phrases.")
|
142 |
+
|
143 |
+
# Prepare data
|
144 |
+
data = load_data('data.json')
|
145 |
+
|
146 |
+
data['Params'] = data['Params'].str.replace('B', '').astype(float)
|
147 |
+
data = data.sort_values(by=AVERAGE_COLUMN_NAME, ascending=False)
|
148 |
+
|
149 |
+
# Closing filters in a expander
|
150 |
+
with st.expander("Filtering benchmark data", icon='🔍'):
|
151 |
+
# Filtering data, e.g. slider for params, average score, etc.
|
152 |
+
col_filter_params, col_filter_average, col_filter_sentiment, col_filter_understanding, col_filter_phraseology = st.columns(5, gap='medium')
|
153 |
+
|
154 |
+
with col_filter_params:
|
155 |
+
params_slider = st.slider("Models Size [B]", min_value=0.0, max_value=float(data['Params'].max()), value=(0.0, float(data['Params'].max())), step=0.1, format="%.1f")
|
156 |
+
data = data[(data['Params'] >= params_slider[0]) & (data['Params'] <= params_slider[1])]
|
157 |
+
|
158 |
+
with col_filter_average:
|
159 |
+
average_slider = st.slider("Average score", step=0.1, min_value=0.0, max_value=5.0, value=(0.0, 5.0))
|
160 |
+
data = data[(data[AVERAGE_COLUMN_NAME] >= average_slider[0]) & (data[AVERAGE_COLUMN_NAME] <= average_slider[1])]
|
161 |
+
|
162 |
+
with col_filter_sentiment:
|
163 |
+
sentiment_slider = st.slider("Sentiment score", step=0.1, min_value=0.0, max_value=5.0, value=(0.0, 5.0))
|
164 |
+
data = data[(data[SENTIMENT_COLUMN_NAME] >= sentiment_slider[0]) & (data[SENTIMENT_COLUMN_NAME] <= sentiment_slider[1])]
|
165 |
+
|
166 |
+
with col_filter_understanding:
|
167 |
+
understanding_slider = st.slider("Understanding score", step=0.1, min_value=0.0, max_value=5.0, value=(0.0, 5.0))
|
168 |
+
data = data[(data[UNDERSTANDING_COLUMN_NAME] >= understanding_slider[0]) & (data[UNDERSTANDING_COLUMN_NAME] <= understanding_slider[1])]
|
169 |
+
|
170 |
+
with col_filter_phraseology:
|
171 |
+
phraseology_slider = st.slider("Phraseology score", step=0.1, min_value=0.0, max_value=5.0, value=(0.0, 5.0))
|
172 |
+
data = data[(data[PHRASEOLOGY_COLUMN_NAME] >= phraseology_slider[0]) & (data[PHRASEOLOGY_COLUMN_NAME] <= phraseology_slider[1])]
|
173 |
+
|
174 |
+
# Extract unique provider names from the "Model" column
|
175 |
+
providers = data["Model"].apply(lambda x: x.split('/')[0].lower()).unique()
|
176 |
+
selected_providers = st.multiselect("Model providers", providers, default=providers)
|
177 |
+
# Filter data based on selected providers
|
178 |
+
data = data[data["Model"].apply(lambda x: x.split('/')[0]).isin(selected_providers)]
|
179 |
+
|
180 |
+
### Display data
|
181 |
+
styled_df_show = style_dataframe(data)
|
182 |
+
styled_df_show = styler(styled_df_show)
|
183 |
+
|
184 |
+
st.data_editor(styled_df_show, column_config={
|
185 |
+
"Model": st.column_config.TextColumn("Model", help="Model name", width="large"),
|
186 |
+
"Params": st.column_config.NumberColumn("Params [B]"),
|
187 |
+
AVERAGE_COLUMN_NAME: st.column_config.NumberColumn(AVERAGE_COLUMN_NAME),
|
188 |
+
RESULTS_COLUMN_NAME: st.column_config.BarChartColumn(
|
189 |
+
"Bar chart of results", help="Summary of the results of each task",
|
190 |
+
y_min=0,y_max=5,),
|
191 |
+
SENTIMENT_COLUMN_NAME: st.column_config.NumberColumn(SENTIMENT_COLUMN_NAME, help='Ability to analyze sentiment'),
|
192 |
+
UNDERSTANDING_COLUMN_NAME: st.column_config.NumberColumn(UNDERSTANDING_COLUMN_NAME, help='Ability to understand language'),
|
193 |
+
PHRASEOLOGY_COLUMN_NAME: st.column_config.NumberColumn(PHRASEOLOGY_COLUMN_NAME, help='Ability to understand phraseological compounds'),
|
194 |
+
}, hide_index=True, disabled=True, height=500)
|
195 |
+
|
196 |
+
# Add selection for models and create a bar chart for selected models using the AVERAGE_COLUMN_NAME, SENTIMENT_COLUMN_NAME, PHRASEOLOGY_COLUMN_NAME, UNDERSTANDING_COLUMN_NAME
|
197 |
+
# Add default selection of 3 best models from AVERAGE_COLUMN_NAME and 1 best model with "Bielik" in Model column
|
198 |
+
default_models = list(data.sort_values(AVERAGE_COLUMN_NAME, ascending=False)['Model'].head(3))
|
199 |
+
bielik_model = data[data['Model'].str.contains('Bielik')].sort_values(AVERAGE_COLUMN_NAME, ascending=False)['Model'].iloc[0]
|
200 |
+
if bielik_model not in default_models:
|
201 |
+
default_models.append(bielik_model)
|
202 |
+
selected_models = st.multiselect("Select models to compare", data["Model"].unique(), default=default_models)
|
203 |
+
selected_data = data[data["Model"].isin(selected_models)]
|
204 |
+
categories = [AVERAGE_COLUMN_NAME, SENTIMENT_COLUMN_NAME, PHRASEOLOGY_COLUMN_NAME, UNDERSTANDING_COLUMN_NAME]
|
205 |
+
|
206 |
+
if selected_models:
|
207 |
+
# Kolorki do wyboru:
|
208 |
+
# colors = px.colors.sample_colorscale("viridis", len(selected_models)+1)
|
209 |
+
colors = px.colors.qualitative.G10[:len(selected_models)]
|
210 |
+
|
211 |
+
fig_bars = go.Figure()
|
212 |
+
for model, color in zip(selected_models, colors):
|
213 |
+
values = selected_data[selected_data['Model'] == model][categories].values.flatten().tolist()
|
214 |
+
fig_bars.add_trace(go.Bar(
|
215 |
+
x=categories,
|
216 |
+
y=values,
|
217 |
+
name=model,
|
218 |
+
marker_color=color
|
219 |
+
))
|
220 |
+
|
221 |
+
# Update layout to use a custom color scale
|
222 |
+
fig_bars.update_layout(
|
223 |
+
showlegend=True,
|
224 |
+
legend=dict(orientation="h", yanchor="top", y=-0.3, xanchor="center", x=0.5),
|
225 |
+
title="Comparison of Selected Models",
|
226 |
+
yaxis_title="Score",
|
227 |
+
template="plotly_dark"
|
228 |
+
)
|
229 |
+
fig_bars.update_yaxes(range=[0, 5.1])
|
230 |
+
st.plotly_chart(fig_bars)
|
231 |
+
|
232 |
+
|
233 |
+
### Zakładka 2 --> Opis
|
234 |
+
with tab2:
|
235 |
+
st.markdown("""
|
236 |
+
### <span style='text-decoration: #FDA428 wavy underline;'>**Cause of Creation**</span>
|
237 |
+
1. **Need**: Models face significant challenges when dealing with understanding complex, context-reliant texts that involve meanings implied beyond the literal content of a statement. Such cases include sarcasm, implicatures, and phraseological compounds.
|
238 |
+
|
239 |
+
Traditional sentiment classifiers typically rely on word-based features (e.g., identifying positive or negative words) to assess sentiment. However, with sarcasm, the literal meaning of words often contradicts the intended sentiment, making it difficult for models to accurately gauge tone. Sarcasm's context-dependence further complicates matters, as these classifiers typically lack the ability to grasp nuanced cues in context, especially when sarcasm is subtle.
|
240 |
+
Similarly, classifiers struggle with implicatures, where the underlying intent is implied rather than explicitly stated. Here, models fail to capture the full sentiment because they rely heavily on surface-level words, missing the non-literal meaning that often drives the sentiment.
|
241 |
+
Phraseological compounds add another layer of difficulty. These are fixed or semi-fixed expressions whose meanings cannot be directly inferred from the individual words. Language models, trained on word-level patterns, often misinterpret these expressions because they fail to recognize the idiomatic or non-literal meaning, leading to inaccurate sentiment analysis.
|
242 |
+
In addition to sentiment analysis, we decided to include the understanding of more complex texts in the benchmark, which was measured by the ability to uncover the intended meaning.
|
243 |
+
|
244 |
+
### <span style='text-decoration: #FDA428 wavy underline;'>**Dataset Information**</span>
|
245 |
+
The dataset contains 200 examples, all written in Polish. Each example consists of the following:
|
246 |
+
- **Main Text**: This is a statement (often an opinion) on any topic that includes a certain type of implicature, often several simultaneously, such as sarcasm or phraseological compounds.
|
247 |
+
- **Reference Sentiment**: The sentiment associated with the main text. We use three categories: negative, neutral, and positive. Ambiguous examples were labeled as "neutral" to exclude them from sentiment classification testing.
|
248 |
+
- **Reference phraseological compounds**: A list of phraseological compounds found in the main text.
|
249 |
+
- **Reference Explanation**: An explanation of the underlying intentions that the author of the main text might have had.
|
250 |
+
|
251 |
+
### <span style='text-decoration: #FDA428 wavy underline;'>**Evaluation Procedure**</span>
|
252 |
+
We distinguish between two models in the evaluation process:
|
253 |
+
- **Evaluated Model**: The model that performs specific tasks, is then assessed based on its performance, and added to a ranking.
|
254 |
+
- **Judge Metamodel**: One of the currently strongest, most versatile LLMs.
|
255 |
+
|
256 |
+
### <span style='text-decoration: #FDA428 wavy underline;'>**GENERATING RESPONSES FROM THE EVALUATED MODEL**</span>
|
257 |
+
1. For each text in the dataset, the evaluated model was required to list the following in three points:
|
258 |
+
- The sentiment (only positive/negative).
|
259 |
+
- The underlying intentions of the author of the text.
|
260 |
+
- All phraseological compounds present in the text along with their meanings in the given context.
|
261 |
+
2. No system prompt is used. The prompt provided to the evaluated model is written in Polish, as we are testing the models in this language. It contains:
|
262 |
+
- **User Prompt**: 3 elements, each consisting of a header written in capital letters and content enclosed in triple quotes:
|
263 |
+
- Information about the role of a careful linguist with extensive experience.
|
264 |
+
- The instruction to perform the three previously described tasks.
|
265 |
+
- The first example of a text that could be included in the dataset.
|
266 |
+
- **Assistant Prompt**: A human-written example answer for the first example text.
|
267 |
+
- **User Prompt**: A second example of a text that could be included in the dataset.
|
268 |
+
- **Assistant Prompt**: A human-written example answer for the second example text.
|
269 |
+
- **User Prompt**: The target text, based on which the evaluated model will be assessed.
|
270 |
+
3. The decision to split the examples into user prompts and assistant prompts was made due to the better results achieved by the vast majority of models. The two examples were selected based on diversity: one has a negative sentiment and several phraseological compounds, while the other is positive and lacks phraseological compounds.
|
271 |
+
|
272 |
+
### <span style='text-decoration: #FDA428 wavy underline;'>**GENERATING METAMODEL EVALUATIONS**</span>
|
273 |
+
1. The purpose of the metamodel is to return the following evaluations:
|
274 |
+
- **Understanding of the Text**: A comparison of the evaluated model's response description to the reference explanation.
|
275 |
+
- **Sentiment Analysis**: An optional evaluation, only if the reference sentiment is "positive" or "negative." We made this decision to exclude texts that people might interpret ambiguously.
|
276 |
+
- **phraseological compounds**: The model is penalized for phrases not included in the reference phraseological compounds. In cases where there are no phraseological compounds, the highest score is awarded only if the model indicates the absence of such expressions — one point is deducted for each excess phrase until the score reaches zero.
|
277 |
+
2. Each evaluation is provided in JSON format. Example of a full response from the metamodel:
|
278 |
+
```json
|
279 |
+
{"WYDŹWIĘK": "5"}
|
280 |
+
{"OCENA": "4"}
|
281 |
+
{"ZWIĄZKI": "3"}
|
282 |
+
```
|
283 |
+
3. The judge metamodel's prompt structure is similar to that of the evaluated model's prompt. No system prompt is used. The prompt includes:
|
284 |
+
- **User Prompt**: 3 elements, each consisting of a header written in capital letters and content enclosed in triple quotes:
|
285 |
+
- **Role**: A reliable assistant who adheres to the instructions and does not perform any other tasks, nor enters any additional text in the response.
|
286 |
+
- **Task**: According to the description in point 1. The comparison of phraseological compounds has the most guidelines, so we noted that the model should focus on this as it is the most challenging step, and that its work will be evaluated based on this point.
|
287 |
+
- The first example of a potential response from the evaluated model along with the references.
|
288 |
+
- **Assistant Prompt**: An example response containing the evaluations.
|
289 |
+
- **User Prompt**: A second example of a potential response from the evaluated model along with the references.
|
290 |
+
- **Assistant Prompt**: An example response containing the evaluations for the second example.
|
291 |
+
- **User Prompt**: The actual response from the evaluated model and the references on which the metamodel will base its evaluations included in the benchmark.
|
292 |
+
4. Here, the examples were also selected based on diversity. One includes a reference with a positive sentiment, while the other contains no reference sentiment at all (an example labeled as "neutral" in the dataset).
|
293 |
+
5. It is worth explaining why we chose this particular process for evaluating phraseological compounds. Initially, we intended to check only those phrases included in the reference and ignore others in the evaluation. Unfortunately, this procedure favored models that provided many phrases that were not phraseological compounds.
|
294 |
+
Therefore, we decided to penalize models for phrases not included in the reference. We aimed to ensure that models were not penalized for providing phraseological compounds we had not included in the reference. After generating the responses, we collected phrases noted by several models and manually reviewed all references to identify phraseological compounds we might have missed.
|
295 |
+
A similar procedure was applied to sentiment analysis—we listed all examples where several models consistently recorded a different sentiment than the reference and reconsidered whether the examples could be interpreted differently than initially assumed.
|
296 |
+
""", unsafe_allow_html=True)
|
297 |
+
|
298 |
+
|
299 |
+
# Ending :)
|
300 |
+
st.markdown("<hr style='border: 1px solid #A85E00;'>", unsafe_allow_html=True)
|
301 |
+
# st.divider()
|
302 |
+
st.markdown("""
|
303 |
+
### Authors:
|
304 |
+
- [Jan Sowa](https://www.linkedin.com/in/janpiotrsowa) - leadership, writing texts, benchmark code
|
305 |
+
- [Agnieszka Kosiak](https://www.linkedin.com/in/agn-kosiak/) - writing texts
|
306 |
+
- [Magdalena Krawczyk](https://www.linkedin.com/in/magdalena-krawczyk-7810942ab/) - writing texts, labeling
|
307 |
+
- [Remigiusz Kinas](https://www.linkedin.com/in/remigiusz-kinas/) - methodological support
|
308 |
+
- [Krzysztof Wróbel](https://www.linkedin.com/in/wrobelkrzysztof/) - engineering, methodological support
|
309 |
+
- [Szymon Baczyński](https://www.linkedin.com/in/szymon-baczynski/) - front-end / streamlit assistant
|
310 |
+
""")
|
311 |
+
|
312 |
+
st.divider()
|
313 |
+
|
314 |
# Run the app with `streamlit run your_script.py`
|