HugoLaurencon commited on
Commit
6ddbf7d
2 Parent(s): 693f997 189d6aa
Files changed (1) hide show
  1. app_2.py +378 -0
app_2.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run with: streamlit run visualization.py
2
+
3
+ import streamlit as st
4
+
5
+ import os
6
+
7
+ import base64
8
+ import json
9
+ import pandas as pd
10
+
11
+ import numpy as np
12
+
13
+ import matplotlib.pyplot as plt
14
+
15
+
16
+ class Visualization:
17
+ def __init__(
18
+ self,
19
+ path_instructions,
20
+ path_data,
21
+ lang,
22
+ num_docs,
23
+ num_docs_for_words,
24
+ max_len_text_display,
25
+ ):
26
+ self.path_instructions = path_instructions
27
+ self.path_data = path_data
28
+ self.lang = lang
29
+ self.num_docs = num_docs
30
+ self.num_docs_for_words = num_docs_for_words
31
+ self.max_len_text_display = max_len_text_display
32
+
33
+ def preamble(self):
34
+ st.markdown(
35
+ "Before diving into this demo, you might want to take a look at how the filtering pipeline of OSCAR looks like in more detail."
36
+ )
37
+
38
+ def get_binary_file_downloader_html(bin_file, file_label="File"):
39
+ with open(bin_file, "rb") as f:
40
+ data = f.read()
41
+ bin_str = base64.b64encode(data).decode()
42
+ href = f'<a href="data:application/octet-stream;base64,{bin_str}" download="{os.path.basename(bin_file)}">{file_label}</a>'
43
+ return href
44
+
45
+ st.markdown(
46
+ get_binary_file_downloader_html(
47
+ self.path_instructions,
48
+ "Download the filtering pipeline of OSCAR as pdf",
49
+ ),
50
+ unsafe_allow_html=True,
51
+ )
52
+
53
+ def open_data(self):
54
+ with open(self.path_data) as json_file:
55
+ data = json.load(json_file)
56
+
57
+ self.num_docs = min(self.num_docs, len(data))
58
+ self.num_docs_for_words = min(self.num_docs_for_words, len(data))
59
+
60
+ if "words" in data[0]:
61
+ words = [doc["words"] for doc in data[: self.num_docs_for_words]]
62
+ words = [word for doc in words for word in doc]
63
+ self.words = pd.DataFrame(words)
64
+ else:
65
+ self.words = None
66
+
67
+ docs = data[: self.num_docs]
68
+ for doc in docs:
69
+ if not (self.words is None):
70
+ del doc["words"]
71
+ if len(doc["text"]) > self.max_len_text_display:
72
+ doc["text"] = (
73
+ doc["text"][: self.max_len_text_display]
74
+ + " [...] [THIS LONG TEXT HAS BEEN TRUNCATED FOR DISPLAY REASONS]"
75
+ )
76
+ self.docs = pd.DataFrame(docs)
77
+
78
+ def set_title(self):
79
+ st.title(f"{self.num_docs} {self.lang} documents from OSCAR with their stats.")
80
+
81
+ def filtering_of_docs(self):
82
+ st.sidebar.subheader("Parameters of the filtering on documents")
83
+
84
+ def set_sliders(docs):
85
+ columns = list(docs)
86
+ keys = []
87
+ conds = {}
88
+
89
+ def get_cond(key, cutoff, max_cutoff):
90
+ if max_cutoff:
91
+ return self.docs[key] <= cutoff
92
+ return self.docs[key] >= cutoff
93
+
94
+ def print_discared_by_cond(cond):
95
+ st.sidebar.caption(
96
+ f"{(len(cond) - np.sum(1*cond)) / len(cond) * 100:.2f}% of the total is discarded with this filter."
97
+ )
98
+ st.sidebar.caption("---------")
99
+
100
+ if "number_words" in columns:
101
+ cutoff_def = "If the number of words of a document is lower than this number, the document is removed."
102
+ max_nb_words = int(np.max(docs["number_words"])) + 1
103
+ cutoff_min_number_words = st.sidebar.slider(
104
+ cutoff_def, 0, min(max_nb_words, 500), 0
105
+ )
106
+ new_key = ("number_words", cutoff_min_number_words, False)
107
+ keys.append(new_key)
108
+ cond_1 = get_cond(new_key[0], new_key[1], new_key[2])
109
+ print_discared_by_cond(cond_1)
110
+
111
+ cutoff_def = "If the number of words of a document is higher than this number, the document is removed."
112
+ cutoff_max_number_words = st.sidebar.slider(
113
+ cutoff_def, 0, max_nb_words, max_nb_words
114
+ )
115
+ new_key = ("number_words", cutoff_max_number_words, True)
116
+ keys.append(new_key)
117
+ cond_2 = get_cond(new_key[0], new_key[1], new_key[2])
118
+ print_discared_by_cond(cond_2)
119
+
120
+ conds["number_words"] = [cond_1, cond_2]
121
+
122
+ if "special_characters_ratio" in columns:
123
+ cutoff_def = "If the special characters ratio of a document is higher than this number, the document is removed."
124
+ cutoff_special_characters_ratio = st.sidebar.slider(
125
+ cutoff_def, 0.0, 1.0, 1.0, step=0.01
126
+ )
127
+ new_key = (
128
+ "special_characters_ratio",
129
+ cutoff_special_characters_ratio,
130
+ True,
131
+ )
132
+ keys.append(new_key)
133
+ cond = get_cond(new_key[0], new_key[1], new_key[2])
134
+ print_discared_by_cond(cond)
135
+ conds["special_characters_ratio"] = [cond]
136
+
137
+ if "stopwords_ratio" in columns:
138
+ cutoff_def = "If the stop words ratio of a document is lower than this number, the document is removed."
139
+ cutoff_stopwords_ratio = st.sidebar.slider(
140
+ cutoff_def, 0.0, 1.0, 0.0, step=0.01
141
+ )
142
+ new_key = ("stopwords_ratio", cutoff_stopwords_ratio, False)
143
+ keys.append(new_key)
144
+ cond = get_cond(new_key[0], new_key[1], new_key[2])
145
+ print_discared_by_cond(cond)
146
+ conds["stopwords_ratio"] = [cond]
147
+
148
+ if "badwords_ratio" in columns:
149
+ cutoff_def = "If the bad words ratio of a document is higher than this number, the document is removed."
150
+ cutoff_badwords_ratio = st.sidebar.slider(
151
+ cutoff_def, 0.0, 1.0, 1.0, step=0.01
152
+ )
153
+ new_key = ("badwords_ratio", cutoff_badwords_ratio, True)
154
+ keys.append(new_key)
155
+ cond = get_cond(new_key[0], new_key[1], new_key[2])
156
+ print_discared_by_cond(cond)
157
+ conds["badwords_ratio"] = [cond]
158
+
159
+ if "lang_id_score" in columns:
160
+ cutoff_def = "If the confidence score for the language identification prediction of a document is lower than this number, the document is removed."
161
+ cutoff_lang_id_score = st.sidebar.slider(
162
+ cutoff_def, 0.0, 1.0, 0.0, step=0.01
163
+ )
164
+ new_key = ("lang_id_score", cutoff_lang_id_score, False)
165
+ keys.append(new_key)
166
+ cond = get_cond(new_key[0], new_key[1], new_key[2])
167
+ print_discared_by_cond(cond)
168
+ conds["lang_id_score"] = [cond]
169
+
170
+ if "perplexity_score" in columns:
171
+ cutoff_def = "If the perplexity score of a document is higher than this number, the document is removed."
172
+ max_pp = int(np.max(docs["perplexity_score"])) + 1
173
+ cutoff_perplexity_score = st.sidebar.slider(
174
+ cutoff_def, 0, max_pp, max_pp
175
+ )
176
+ new_key = ("perplexity_score", cutoff_perplexity_score, True)
177
+ keys.append(new_key)
178
+ cond = get_cond(new_key[0], new_key[1], new_key[2])
179
+ print_discared_by_cond(cond)
180
+ conds["perplexity_score"] = [cond]
181
+
182
+ return keys, conds
183
+
184
+ self.keys, conds = set_sliders(self.docs)
185
+
186
+ all_conds = [subcond for cond in list(conds.values()) for subcond in cond]
187
+ all_conds = np.all(all_conds, axis=0)
188
+
189
+ st.header("Filtering on documents")
190
+
191
+ def display_dataset(cond, description):
192
+ displayed_docs = self.docs.loc[cond]
193
+ st.subheader(
194
+ f"{description}: {len(displayed_docs)} docs ({len(displayed_docs) / self.num_docs * 100:.2f}%)"
195
+ )
196
+ st.markdown(
197
+ "Click on a column to sort by it, place the cursor on the text to display it."
198
+ )
199
+ st.dataframe(displayed_docs)
200
+
201
+ display_dataset(np.invert(all_conds), "Discarded documents")
202
+
203
+ # st.subheader("Display discarded documents by filter")
204
+ display_discarded_documents_by_filter = st.checkbox(
205
+ "Display discarded documents by filter"
206
+ )
207
+
208
+ if display_discarded_documents_by_filter:
209
+ columns = list(self.docs)
210
+
211
+ if "number_words" in columns:
212
+ cond_filter = np.invert(np.all(conds["number_words"], axis=0))
213
+ display_dataset(
214
+ cond_filter,
215
+ "Discarded documents for the filter on the number of words",
216
+ )
217
+
218
+ if "special_characters_ratio" in columns:
219
+ cond_filter = np.invert(
220
+ np.all(conds["special_characters_ratio"], axis=0)
221
+ )
222
+ display_dataset(
223
+ cond_filter,
224
+ "Discarded documents for the filter on the special characters ratio",
225
+ )
226
+
227
+ if "stopwords_ratio" in columns:
228
+ cond_filter = np.invert(np.all(conds["stopwords_ratio"], axis=0))
229
+ display_dataset(
230
+ cond_filter,
231
+ "Discarded documents for the filter on the stop words ratio",
232
+ )
233
+
234
+ if "badwords_ratio" in columns:
235
+ cond_filter = np.invert(np.all(conds["badwords_ratio"], axis=0))
236
+ display_dataset(
237
+ cond_filter,
238
+ "Discarded documents for the filter on the bad words ratio",
239
+ )
240
+
241
+ if "lang_id_score" in columns:
242
+ cond_filter = np.invert(np.all(conds["lang_id_score"], axis=0))
243
+ display_dataset(
244
+ cond_filter,
245
+ "Discarded documents for the filter on the language identification confidence score",
246
+ )
247
+
248
+ if "perplexity_score" in columns:
249
+ cond_filter = np.invert(np.all(conds["perplexity_score"], axis=0))
250
+ display_dataset(
251
+ cond_filter,
252
+ "Discarded documents for the filter on the perplexity score",
253
+ )
254
+
255
+ display_dataset(all_conds, "Retained documents")
256
+
257
+ def filtering_of_words(self):
258
+ if not (self.words is None):
259
+ st.sidebar.subheader("Parameter of the filtering on words")
260
+
261
+ cutoff_def = "If the length of a word is higher than this number, the word is removed."
262
+ max_len_word = min(int(np.max(self.words["len_word"])) + 1, 200)
263
+ cutoff_word = st.sidebar.slider(cutoff_def, 0, max_len_word, max_len_word)
264
+
265
+ incorrect_substrings = st.sidebar.checkbox(
266
+ "Remove words with incorrect substrings."
267
+ )
268
+
269
+ cond_words = self.words["len_word"] <= cutoff_word
270
+ if incorrect_substrings:
271
+ cond_words = cond_words & np.invert(self.words["incorrect_substring"])
272
+
273
+ st.header("Filtering on words")
274
+
275
+ st.markdown(
276
+ f"Since the number of words is way larger than the number of documents, "
277
+ f"we consider in this section words for the first {self.num_docs_for_words} documents only."
278
+ )
279
+
280
+ discarded_words = self.words.loc[np.invert(cond_words)]
281
+ st.subheader(
282
+ f"Discarded words: {len(discarded_words)} words ({len(discarded_words) / len(self.words) * 100:.2f}%)"
283
+ )
284
+ st.markdown(
285
+ "Click on a column to sort by it, place the cursor on the text to display it."
286
+ )
287
+ st.dataframe(discarded_words)
288
+
289
+ retained_words = self.words.loc[cond_words]
290
+ st.subheader(
291
+ f"Retained words: {len(retained_words)} words ({len(retained_words) / len(self.words) * 100:.2f}%)"
292
+ )
293
+ st.markdown(
294
+ "Click on a column to sort by it, place the cursor on the text to display it."
295
+ )
296
+ st.dataframe(retained_words)
297
+
298
+ def plot_distributions_filtering_parameters(self):
299
+ st.header("Distributions of the filtering parameters")
300
+
301
+ display_distributions = st.checkbox("Display distributions")
302
+
303
+ if display_distributions:
304
+
305
+ def plot_hist(dataframe, key, num_bins=50):
306
+ st.subheader(" ".join(key.split("_")))
307
+ hist_values = dataframe[key].values
308
+ max_range = np.max(hist_values)
309
+ hist_values = np.histogram(
310
+ hist_values, bins=num_bins, range=(0, max_range)
311
+ )[0]
312
+ st.bar_chart(hist_values)
313
+ st.markdown(f"Each bin is of size: {max_range/num_bins}.")
314
+
315
+ for key in list({el[0]: None for el in self.keys}):
316
+ plot_hist(self.docs, key)
317
+
318
+ if not (self.words is None):
319
+ plot_hist(self.words, "len_word")
320
+
321
+ def plot_zipf_law(self):
322
+ if not (self.words is None):
323
+ st.header("Zipf's Law")
324
+
325
+ display_zipf_law = st.checkbox("Display Zipf's Law")
326
+
327
+ if display_zipf_law:
328
+
329
+ freq_words = {}
330
+ for _, row in self.words.iterrows():
331
+ freq_words[row["word"]] = freq_words.get(row["word"], 0) + 1
332
+ freq_words = np.array(list(freq_words.values()))
333
+ freq_words = -np.sort(-freq_words)
334
+
335
+ fig, ax = plt.subplots()
336
+ ax.loglog(freq_words)
337
+ ax.set_title("Zipf's Law")
338
+ ax.set_xlabel("$i$-th most frequent word")
339
+ ax.set_ylabel("frequency in the documents")
340
+ st.pyplot(fig)
341
+
342
+ def download_data(self):
343
+ st.header("Download data")
344
+
345
+ with open(self.path_data) as json_file:
346
+ btn = st.download_button(
347
+ label="Download data as json",
348
+ data=json_file,
349
+ file_name="data.json",
350
+ )
351
+
352
+ def visualization(self):
353
+ self.preamble()
354
+ self.open_data()
355
+ self.set_title()
356
+ self.filtering_of_docs()
357
+ self.filtering_of_words()
358
+ self.plot_distributions_filtering_parameters()
359
+ #self.plot_zipf_law()
360
+ self.download_data()
361
+
362
+
363
+ path_instructions = "./filtering_pipeline_oscar.pdf"
364
+ path_data = "./zh_examples_with_stats.json"
365
+ lang = "Chinese"
366
+ num_docs = 5000
367
+ num_docs_for_words = 500
368
+ max_len_text_display = 10000
369
+
370
+ visualization = Visualization(
371
+ path_instructions,
372
+ path_data,
373
+ lang,
374
+ num_docs,
375
+ num_docs_for_words,
376
+ max_len_text_display,
377
+ )
378
+ visualization.visualization()