-
Notifications
You must be signed in to change notification settings - Fork 12
/
app.py
1804 lines (1644 loc) · 70.4 KB
/
app.py
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import glob
import os
# Need this here to prevent errors
os.environ["PERSISTENT"] = "True"
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.io as pio
import streamlit as st
from nltk.corpus import stopwords
from streamlit import caching
from app_utils import (
get_curve_hull_objects,
get_default_args,
get_dict_with_new_words,
get_frequency_for_range,
get_productivity_for_range,
get_word_pair_sim_bw_models,
get_years_from_data_path,
read_text_file,
word_to_entry_dict,
)
from preprocess_and_save_txt import preprocess_and_save
from session import _get_state
from src.analysis.productivity_inference import cluster_productivity
from src.analysis.semantic_drift import find_most_drifted_words
from src.analysis.similarity_acc_matrix import (
compute_acc_between_years,
compute_acc_heatmap_between_years,
)
from src.analysis.topic_extraction_lda import extract_topics_lda
from src.analysis.track_trends_sim import compute_similarity_matrix_years
from src.analysis.tracking_clusters import kmeans_clustering, kmeans_embeddings
from src.utils import get_word_embeddings, plotly_line_dataframe, word_cloud
from src.utils.misc import get_sub, reduce_dimensions
from src.utils.statistics import freq_top_k, yake_keyword_extraction
from src.utils.viz import (
embs_for_plotting,
plotly_heatmap,
plotly_histogram,
plotly_scatter,
plotly_scatter_df,
)
from train_twec import train
template = "simple_white"
pio.templates.default = template
plotly_template = pio.templates[template]
colorscale = plotly_template.layout["colorscale"]["diverging"]
# Folder selection not directly support in Streamlit as of now
# https://github.com/streamlit/streamlit/issues/1019
# import tkinter as tk
# from tkinter import filedialog
# root = tk.Tk()
# root.withdraw()
# # Make folder picker dialog appear on top of other windows
# root.wm_attributes('-topmost', 1)
np.random.seed(42)
pos_tag_dict = {}
with open("nltk_pos_tag_list.txt") as f:
for line in f:
line_split = line.strip().split("\t")
tag = line_split[0]
desc = line_split[1]
pos_tag_dict[tag] = desc
# @st.cache(allow_output_mutation=True)
# def get_sim_dict():
# return OrderedDict()
def plot(obj, col1, col2, typ="plotly", key="key"):
formats = [".eps", ".pdf", ".svg", ".png", ".jpeg", ".webp"]
col2.header("Save your graph")
if typ == "plotly":
formats.append(".html")
col1.plotly_chart(obj, use_container_width=True)
col2.write(
"**Note:** You can also save a particular portion of the graph using the camera icon on the chart."
)
elif typ == "pyplot":
col1.pyplot(obj)
elif typ == "array":
col1.image(obj)
elif typ == "PIL":
formats.remove(".svg")
col1.image(obj)
name = col2.text_input("Name", value="MyFigure", key=key)
format = col2.selectbox(
"Format", formats, help="The format to be used to save the file.", key=key
)
# Caveat: This only works on local host. See comment https://github.com/streamlit/streamlit/issues/1019#issuecomment-813001320
# Caveat 2: The folder selection can only be done once and not repetitively
# dirname = st.text_input('Selected folder:', filedialog.askdirectory(master=root))
if col2.button("Save", key=key):
with st.spinner(text="Saving"):
save_name = f"{name}{format}"
if typ == "plotly":
if format == ".html":
obj.write_html(save_name)
else:
obj.write_image(save_name, width=1920, height=1080)
elif typ == "array":
plt.imsave(save_name, obj)
elif typ == "pyplot":
plt.savefig(save_name)
elif typ == "PIL":
obj.save(save_name)
def display_caching_option(element):
col1, col2 = element.beta_columns(2)
if col1.checkbox("Persistent Caching", value=False):
caching._clear_mem_cache()
os.environ["PERSISTENT"] = "True"
else:
caching._clear_disk_cache()
os.environ["PERSISTENT"] = "False"
if col2.button("Clear All Cache"):
caching.clear_cache()
def get_component(component_var, typ, params):
return component_var.__getattribute__(typ)(**params)
def generate_components_from_dict(comp_dict, variable_params):
vars_ = {}
for component_key, component_dict in comp_dict.items():
component_var = component_dict["component_var"]
typ = component_dict["typ"]
params = component_dict["params"]
component_variable_params = component_dict["variable_params"]
params.update(
{
key: variable_params[value]
for key, value in component_variable_params.items()
}
)
vars_[component_key] = get_component(component_var, typ, params)
return vars_
def generate_analysis_components(analysis_type, variable_params):
sidebar_summary_text.write(ANALYSIS_METHODS[analysis_type]["SUMMARY"])
vars_ = generate_components_from_dict(
ANALYSIS_METHODS[analysis_type]["COMPONENTS"], variable_params
)
figure1_title.header(analysis_type)
with about.beta_expander("About"):
st.markdown(ANALYSIS_METHODS[analysis_type]["ABOUT"], unsafe_allow_html=True)
return vars_
st.set_page_config(
page_title="DRIFT",
layout="wide",
initial_sidebar_state="expanded",
page_icon="./misc/images/logo_letter_png.png",
)
state = _get_state()
# LAYOUT
main = st.beta_container()
title = main.empty()
settings = main.empty()
figure1_block = main.beta_container()
figure2_block = main.beta_container()
figure1_title = figure1_block.empty()
about = figure1_block.empty()
figure1_params = figure1_block.beta_container()
figure1_plot = figure1_block.beta_container()
figure2_title = figure2_block.empty()
figure2_params = figure2_block.beta_container()
figure2_plot = figure2_block.beta_container()
sidebar = st.sidebar.beta_container()
sidebar_image = sidebar.empty()
sidebar_title = sidebar.empty()
sidebar_mode = sidebar.empty()
sidebar_settings = sidebar.beta_container()
sidebar_analysis_type = sidebar.empty()
sidebar_summary_header = sidebar.empty()
sidebar_summary_text = sidebar.empty()
sidebar_parameters = sidebar.beta_container()
# Analysis Methods Resource Bundle
# COMMON RESOURCES
COMMON = dict(
TITLE="DRIFT: Diachronic Analysis of Scientific Literature",
SIDEBAR_TITLE="Settings",
SIDEBAR_SUMMARY_HEADER="Summary",
STOPWORDS=list(set(stopwords.words("english"))),
)
ANALYSIS_METHODS = {
"WordCloud": dict(
ABOUT='''A word cloud, or tag cloud, is a textual data visualization which allows anyone to see in a single glance the words which have the highest frequency within a given body of text. Word clouds are typically used as a tool for processing, analyzing and disseminating qualitative sentiment data.
References:
- [Word Cloud Explorer: Text Analytics based on Word Clouds](https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=6758829)
- [wordcloud Package](https://amueller.github.io/word_cloud/generated/wordcloud.WordCloud.html)
- [Free Word Cloud Generator](https://www.freewordcloudgenerator.com)
''',
SUMMARY="WordClouds are visual representation of text data, used to depict the most frequent words in the corpus. The depictions are usually single words, and the frequency is shown with font size.",
COMPONENTS=dict(
data_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Data Path",
value="./data/",
help="Directory path to the folder containing year-wise text files.",
),
),
max_words=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "max_words"},
params=dict(
label="#words (max)",
min_value=10,
format="%d",
help="Maximum number of words to be displayed",
),
),
min_font_size=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "min_font_size"},
params=dict(
label="Min. font size", min_value=10, max_value=80, format="%d"
),
),
max_font_size=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "max_font_size"},
params=dict(
label="Max. font size", min_value=25, max_value=100, format="%d"
),
),
background_color=dict(
component_var=sidebar_parameters,
typ="color_picker",
variable_params={"value": "background_color"},
params=dict(label="Background Color"),
),
width=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "width"},
params=dict(
label="Width", min_value=100, max_value=10000, format="%d", step=50
),
),
height=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "height"},
params=dict(
label="Height",
min_value=100,
max_value=10000,
format="%d",
step=50,
),
),
collocations=dict(
component_var=sidebar_parameters,
typ="checkbox",
variable_params={"value": "collocations"},
params=dict(
label="Collocations",
help="Whether to include collocations (bigrams) of two words.",
),
),
),
),
"Productivity/Frequency Plot": dict(
ABOUT=r'''Our main reference for this method is [this paper](https://www.aclweb.org/anthology/W16-2101.pdf).
In short, this paper uses normalized term frequency and term producitvity as their measures.
- **Term Frequency**: This is the normalized frequency of a given term in a given year.
- **Term Productivity**: This is a measure of the ability of the concept to produce new multi-word terms. In our case we use bigrams. For each year *y* and single-word term *t*, and associated *n* multi-word terms *m*, the productivity is given by the entropy:
$$
e(t,y) = - \sum_{i=1}^{n} \log_{2}(p_{m_{i},y}).p_{m_{i},y}
\\
p_{m,y} = \frac{f(m)}{\sum_{i=1}^{n}f(m_{i})}
$$
Based on these two measures, they hypothesize three kinds of terms:
- **Growing Terms**: Those which have increasing frequency and productivity in the recent years.
- **Consolidated Terms**: Those that are growing in frequency, but not in productivity.
- **Terms in Decline**: Those which have reached an upper bound of productivity and are being used less in terms of frequency.
Then, they perform clustering of the terms based on their frequency and productivity curves over the years to test their hypothesis.
They find that the clusters formed show similar trends as expected.
**Note**: They also evaluate quality of their clusters using pseudo-labels, but we do not use any automated labels here. They also try with and without double-counting multi-word terms, but we stick to double-counting. They suggest it is more explanable.
''',
SUMMARY="Term productivity, that is, a measure for the ability of a concept (lexicalised as a singleword term) to produce new, subordinated concepts (lexicalised as multi-word terms).",
COMPONENTS=dict(
data_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Data Path",
value="./data/",
help="Directory path to the folder containing year-wise text files.",
),
),
n=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "n"},
params=dict(
label="N",
min_value=1,
format="%d",
help="N in N-gram for productivity calculation.",
),
),
top_k=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "top_k"},
params=dict(
label="K",
min_value=0,
format="%d",
help="Top-K words to be chosen from.",
),
),
filter_pos_tags=dict(
component_var=sidebar_parameters,
typ="multiselect",
variable_params={"default": "filter_pos_tags"},
params=dict(
label="POS-Tags Filter",
options=list(pos_tag_dict.keys()),
format_func=lambda x: x + " : " + pos_tag_dict[x],
help="The POS Tags that should be selected. If empty, no filtering is done.",
),
),
tfidf=dict(
component_var=sidebar_parameters,
typ="checkbox",
variable_params={"value": "tfidf"},
params=dict(
label="Use TF-IDF",
help="Whether to use TF-IDF for selection instead of frequency.",
),
),
normalize=dict(
component_var=sidebar_parameters,
typ="checkbox",
variable_params={"value": "normalize"},
params=dict(
label="Normalize",
help="Whether to use normalize frequency.",
),
),
),
),
"Acceleration Plot": dict(
ABOUT=r'''This plot is based on the word-pair acceleration over time. Our inspiration for this method is [this paper](https://sci-hub.se/10.1109/ijcnn.2019.8852140).
Acceleration is a metric which calculates how quickly the word embeddings for a pair of word get close together or farther apart. If they are getting closer together, it means these two terms have started appearing more frequently in similar contexts, which leads to similar embeddings.
In the paper, it is described as:
$$
acceleration(w_{i}, w_{j}) = sim(w_{i}, w_{j})^{t+1} - sim(w_{i}, w_{j})^{t}\\
sim(w_{i}, w_{j}) = cosine (u_{w_{i}}, u_{w_{j}}) = \frac{u_{w_{i}}.u_{w_{j}}}{\left\lVert u_{w_{i}}\right\rVert . \left\lVert u_{w_{j}}\right\rVert}
$$
Below, we display the top few pairs between the given start and end year in dataframe, then one can select years and then select word-pairs in the plot parameters expander. A reduced dimension plot is displayed.
**Note**: They suggest using skip-gram method over CBOW for the model. They use t-SNE representation to view the embeddings. But their way of aligning the embeddings is different. They also use some stability measure to find the best Word2Vec model. The also use *Word2Phrase* which we are planning to add soon.
''',
SUMMARY="A pair of words converges/diverges over time. Acceleration is a measure of convergence of a pair of keywords. This module identifies fast converging keywords and depicts this convergence on a 2-D plot.",
COMPONENTS=dict(
note=dict(
component_var=figure1_block,
typ="info",
variable_params={},
params=dict(
body="Note that all words may not be present in all years. In that case mean of all word vectors is taken."
),
),
data_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Data Path",
value="./data/",
help="Directory path to the folder containing year-wise text files.",
),
),
model_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Model Dir",
value="./model/",
help="Directory path to the folder containing year-wise model files.",
),
),
top_k=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "top_k"},
params=dict(
label="K",
min_value=1,
format="%d",
help="Top-K words to be chosen from.",
),
),
filter_pos_tags=dict(
component_var=sidebar_parameters,
typ="multiselect",
variable_params={"default": "filter_pos_tags"},
params=dict(
label="POS-Tags Filter",
options=list(pos_tag_dict.keys()),
format_func=lambda x: x + " : " + pos_tag_dict[x],
help="The POS Tags that should be selected. If empty, no filtering is done.",
),
),
tfidf=dict(
component_var=sidebar_parameters,
typ="checkbox",
variable_params={"value": "tfidf"},
params=dict(
label="Use TF-IDF",
help="Whether to use TF-IDF for selection instead of frequency.",
),
),
top_k_sim=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "top_k_sim"},
params=dict(
label="K (sim.)",
min_value=2,
format="%d",
help="Top-K words for similarity.",
),
),
top_k_acc=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "top_k_acc"},
params=dict(
label="K (acc.)",
min_value=1,
format="%d",
help="Top-K words to be reported for acceleration.",
),
),
p2f=dict(
component_var=sidebar_parameters,
typ="checkbox",
variable_params={},
params=dict(
label="Past→Future",
value=True,
help="Whether to calculate past to future acceleration",
),
),
),
),
"Semantic Drift": dict(
ABOUT=r'''This plot represents the change in meaning of a word over time. This shift is represented on a 2-dimensional representation of the embedding space.
To find the drift of a word, we calculate the distance between the embeddings of the word in the final year and in the initial year. We find the drift for all words and sort them in descending order to find the most drifted words.
We give an option to use one of two distance metrics: Euclidean Distance and Cosine Distance.
$$
euclidean\_distance = \sqrt{\vec{u}.\vec{u} - 2 \times \vec{u}.\vec{v} + \vec{v}.\vec{v}} \\
cosine\_distance = 1 - \frac{\vec{u}.\vec{v}}{||\vec{u}||||\vec{v}||}
$$
We plot top-K (sim.) most similar words around the two representations of the selected word.
In the ```Plot Parameters``` expander, the user can select the range of years over which the drift will be computed. He/She can also select the dimensionality reduction method for plotting the embeddings.
Below the graph, we provide a list of most drifted words (from the top-K keywords). The user can also choose a custom word.
''',
SUMMARY="Computing the semantic drift of words, i.e., change in meaning, by finding the Euclidean/Cosine Distance between two representations of the word from different years and showing the drift on a t-SNE plot",
COMPONENTS=dict(
data_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Data Path",
value="./data/",
help="Directory path to the folder containing year-wise text files.",
),
),
model_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Model Dir",
value="./model/",
help="Directory path to the folder containing year-wise model files.",
),
),
top_k=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "top_k"},
params=dict(
label="K",
value=200,
min_value=1,
format="%d",
help="Top-K words on which we will calculate drift.",
),
),
filter_pos_tags=dict(
component_var=sidebar_parameters,
typ="multiselect",
variable_params={"default": "filter_pos_tags"},
params=dict(
label="POS-Tags Filter",
options=list(pos_tag_dict.keys()),
format_func=lambda x: x + " : " + pos_tag_dict[x],
help="The POS Tags that should be selected. If empty, no filtering is done.",
),
),
tfidf=dict(
component_var=sidebar_parameters,
typ="checkbox",
variable_params={"value": "tfidf"},
params=dict(
label="Use TF-IDF",
help="Whether to use TF-IDF for selection instead of frequency.",
),
),
top_k_sim=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "top_k_sim"},
params=dict(
label="K (sim.)",
min_value=1,
format="%d",
help="Top-K words for similarity.",
),
),
top_k_drift=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "top_k_drift"},
params=dict(
label="K (drift.)",
min_value=1,
format="%d",
help="Top-K words for drift.",
),
),
distance_measure=dict(
component_var=sidebar_parameters,
typ="selectbox",
variable_params={},
params=dict(
label="Distance Method",
options=["euclidean", "cosine"],
help="Distance Method to compute the drift.",
),
),
),
),
"Tracking Clusters": dict(
ABOUT=r'''Word meanings change over time. They come closer or drift apart. In a certain year, words are clumped together, i.e., they belong to one cluster. But over time, clusters can break into two/coalesce together to form one. Unlike the previous module which tracks movement of one word at a time, here, we track the movement of clusters.
We plot the formed clusters for all the years lying in the selected range of years.
**Note:** We give an option to use one of two libraries for clustering: sklearn or faiss. faiss' KMeans implementation is around 10 times faster than sklearn's.
''',
SUMMARY="Cluster word embeddings for different years and track how these clusters change over a time period.",
COMPONENTS=dict(
data_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Data Path",
value="./data/",
help="Directory path to the folder containing year-wise text files.",
),
),
model_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Model Dir",
value="./model/",
help="Directory path to the folder containing year-wise model files.",
),
),
top_k=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "top_k"},
params=dict(
label="K",
min_value=1,
format="%d",
help="Top-K words to be chosen from.",
),
),
filter_pos_tags=dict(
component_var=sidebar_parameters,
typ="multiselect",
variable_params={"default": "filter_pos_tags"},
params=dict(
label="POS-Tags Filter",
options=list(pos_tag_dict.keys()),
format_func=lambda x: x + " : " + pos_tag_dict[x],
help="The POS Tags that should be selected. If empty, no filtering is done.",
),
),
tfidf=dict(
component_var=sidebar_parameters,
typ="checkbox",
variable_params={"value": "tfidf"},
params=dict(
label="Use TF-IDF",
help="Whether to use TF-IDF for selection instead of frequency.",
),
),
n_clusters=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={},
params=dict(
label="Number of clusters",
min_value=0,
value=0,
format="%d",
help="Number of clusters. If set to 0, optimal number of clusters are found using the silhouette score.",
),
),
max_clusters=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "k_max"},
params=dict(
label="Max number of clusters",
min_value=1,
value=0,
format="%d",
help="Maximum number of clusters. Used when number of clusters is 0.",
),
),
method=dict(
component_var=sidebar_parameters,
typ="selectbox",
variable_params={},
params=dict(
label="Method",
options=["faiss", "sklearn"],
help="Method to use for K-means. `faiss` is recommended when calculating optimal number of clusters.",
),
),
),
),
"Acceleration Heatmap": dict(
ABOUT=r'''This plot is based on the word-pair acceleration over time. Our inspiration for this method is [this paper](https://sci-hub.se/10.1109/ijcnn.2019.8852140).
Acceleration is a metric which calculates how quickly the word embeddings for a pair of word get close together or farther apart. If they are getting closer together, it means these two terms have started appearing more frequently in similar contexts, which leads to similar embeddings.
In the paper, it is described as:
$$
acceleration(w_{i}, w_{j}) = sim(w_{i}, w_{j})^{t+1} - sim(w_{i}, w_{j})^{t}\\
sim(w_{i}, w_{j}) = cosine (u_{w_{i}}, u_{w_{j}}) = \frac{u_{w_{i}}.u_{w_{j}}}{\left\lVert u_{w_{i}}\right\rVert . \left\lVert u_{w_{j}}\right\rVert}
$$
For all the selected keywords, we display a heatmap, where the brightness of the colour determines the value of the acceleration between that pair, i.e., the brightness is directly proportional to the acceleration value.
**Note**: They suggest using skip-gram method over CBOW for the model.
''',
SUMMARY="A pair of words converges/diverges over time. Acceleration is a measure of convergence of a pair of keywords. This module identifies fast converging keywords and depicts the convergence using a heatmap.",
COMPONENTS=dict(
note=dict(
component_var=figure1_params,
typ="info",
variable_params={},
params=dict(
body="Note that all words may not be present in all years. In that case mean of all word vectors is taken."
),
),
data_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Data Path",
value="./data/",
help="Directory path to the folder containing year-wise text files.",
),
),
model_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Model Dir",
value="./model/",
help="Directory path to the folder containing year-wise model files.",
),
),
top_k=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "top_k"},
params=dict(
label="K",
min_value=1,
format="%d",
help="Top-K words to be chosen from.",
),
),
filter_pos_tags=dict(
component_var=sidebar_parameters,
typ="multiselect",
variable_params={"default": "filter_pos_tags"},
params=dict(
label="POS-Tags Filter",
options=list(pos_tag_dict.keys()),
format_func=lambda x: x + " : " + pos_tag_dict[x],
help="The POS Tags that should be selected. If empty, no filtering is done.",
),
),
tfidf=dict(
component_var=sidebar_parameters,
typ="checkbox",
variable_params={"value": "tfidf"},
params=dict(
label="Use TF-IDF",
help="Whether to use TF-IDF for selection instead of frequency.",
),
),
p2f=dict(
component_var=sidebar_parameters,
typ="checkbox",
variable_params={},
params=dict(
label="Year 1 → Year 2",
value=True,
help="Whether to calculate Year 1 to Year 2 acceleration",
),
),
),
),
"Track Trends with Similarity": dict(
ABOUT=r'''In this method, we wish to chart the trajectory of a word/topic from year 1 to year 2.
To accomplish this, we allow the user to pick a word from year 1. At the same time, we ask the user to provide the desired stride. We search for the most similar word in the next stride years. We keep doing this iteratively till we reach year 2, updating the word at each step.
The user has to select a word and click on ```Generate Dataframe```. This gives a list of most similar words in the next stride years. The user can now iteratively select the next word from the drop-down till the final year is reached.
''',
SUMMARY="We identify trends by recursively finding most similar words over years. In this way, we are able to chart the trajectory of a word from one year to another.",
COMPONENTS=dict(
data_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Data Path",
value="./data/",
help="Directory path to the folder containing year-wise text files.",
),
),
model_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Model Dir",
value="./model/",
help="Directory path to the folder containing year-wise model files.",
),
),
top_k=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "top_k"},
params=dict(
label="K",
min_value=1,
format="%d",
help="Top-K words to be chosen from.",
),
),
filter_pos_tags=dict(
component_var=sidebar_parameters,
typ="multiselect",
variable_params={"default": "filter_pos_tags"},
params=dict(
label="POS-Tags Filter",
options=list(pos_tag_dict.keys()),
format_func=lambda x: x + " : " + pos_tag_dict[x],
help="The POS Tags that should be selected. If empty, no filtering is done.",
),
),
tfidf=dict(
component_var=sidebar_parameters,
typ="checkbox",
variable_params={"value": "tfidf"},
params=dict(
label="Use TF-IDF",
help="Whether to use TF-IDF for selection instead of frequency.",
),
),
top_k_sim=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "top_k_sim"},
params=dict(
label="K (sim.)",
min_value=1,
format="%d",
help="Top-K words for similarity.",
),
),
stride=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "stride"},
params=dict(
label="Stride",
min_value=1,
format="%d",
help="Stride",
),
),
),
),
"Keyword Visualisation": dict(
ABOUT=r'''Here, we use the [YAKE Keyword Extraction](https://www.sciencedirect.com/science/article/abs/pii/S0020025519308588) method to extract keywords.
In our code, we use an [open source implementation](https://github.com/LIAAD/yake) of YAKE.
**NOTE:** Yake returns scores which are indirectly proportional to the keyword importance. Hence, we do the following to report the final scores:
$$
new\_score = \frac{1}{10^{5} \times yake\_score}
$$
''',
SUMMARY="Bar Graph visualisations for keywords (words vs score).",
COMPONENTS=dict(
data_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Data Path",
value="./data/",
help="Directory path to the folder containing year-wise text files.",
),
),
top_k=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "top_k"},
params=dict(
label="K",
min_value=1,
format="%d",
help="Top-K words to be chosen from.",
),
),
max_ngram_size=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "max_ngram_size"},
params=dict(
label="Max Ngram Size",
min_value=1,
value=2,
format="%d",
help="N-gram size.",
),
),
),
),
"LDA Topic Modelling": dict(
ABOUT=r'''[Latent Dirichlet Allocation](https://www.jmlr.org/papers/volume3/blei03a/blei03a.pdf) is a generative probabilistic model for an assortment of documents, generally used for topic modelling and extraction. LDA clusters the text data into imaginary topics.
Every topic can be represented as a probability distribution over ngrams and every document can be represented as a probability distribution over these generated topics.
We train LDA on a corpus where each document contains the abstracts of a particular year. We express every year as a probability distribution of topics.
In the first bar graph, we show how a year can be decomposed into topics. The graphs below the first one show a decomposition of the relevant topics.
''',
SUMMARY="LDA clusters the text data into imaginary topics. Every topic can be represented as a probability distribution over ngrams and every document can be represented as a probability distribution over these generated topics.",
COMPONENTS=dict(
data_path=dict(
component_var=sidebar_parameters,
typ="text_input",
variable_params={},
params=dict(
label="Data Path",
value="./data/",
help="Directory path to the folder containing year-wise text files.",
),
),
num_topics=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "num_topics"},
params=dict(
label="Number of Topics",
min_value=0,
value=0,
format="%d",
help="Number of LDA Topics",
),
),
num_words=dict(
component_var=sidebar_parameters,
typ="number_input",
variable_params={"value": "num_words"},
params=dict(
label="Number of Words",
min_value=10,
value=10,
format="%d",
help="Number of Words Per Topic.",
),
),
),
),
}
PREPROCESS = dict(
ABOUT="",
SUMMARY="",
COMPONENTS=dict(
json_path=dict(
component_var=st,
typ="text_input",
variable_params={"value": "json_path"},
params=dict(
label="JSON Path", help="Path to the JSON file containing raw data"
),
),
text_key=dict(
component_var=st,
typ="text_input",
variable_params={"value": "text_key"},
params=dict(label="Text Key", help="Key in JSON containing the text"),
),
save_dir=dict(
component_var=st,
typ="text_input",
variable_params={"value": "save_dir"},
params=dict(
label="Data Path",
help="Directory path to the folder where you want to store year-wise processed text files.",
),
),
),