-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.py
2395 lines (2126 loc) · 104 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 os
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_uploader as du
import uuid
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State,MATCH, ALL
from dash.exceptions import PreventUpdate
import dash_table
import plotly.graph_objs as go
import dash_daq as daq
import plotly.express as px
from wordcloud import WordCloud, STOPWORDS
import pandas as pd
import re
import json
from os import listdir
from os.path import isfile, join
from whoosh_search import preprocess_corpus
from topic_model import word2vec
from topic_model import generate_models_fromapp
import base64
import io
import time
import urllib
from flask import Flask
UPLOAD_FOLDER_ROOT="./upload"
server = Flask("__main__")
app = dash.Dash(server=server,
meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}]
)
#server = app.server
app.config["suppress_callback_exceptions"] = True
du.configure_upload(app, UPLOAD_FOLDER_ROOT)
# read uploaded corpus names
corpus = pd.read_pickle("./corpus_save").to_dict()
if (len(corpus)>0): #not empty
corpus = corpus[0]
# --- build left banner ---
def build_banner(corpus_element,saves_element,loaded):
added_option=[]
if len(loaded["added"])>0:
i=0
for add in loaded["added"]:
added_option.append(html.Div([dcc.Checklist(id={'type':'selected','index':i},
options=[{'label': add, 'value': add}],
labelClassName="selected-term2" )]
))
i+=1
# find number of document in each year
doc_num_year=preprocess_corpus.get_num_doc_year(corpus[corpus_element['props']['value']])
year_list=[int(y) for y in sorted(list(doc_num_year.keys()))]
# generate layout
return html.Div(
id="banner",
className="banner",
children=[
html.Div(
id="banner-text",
children=[],
),
html.Div(style={"visibility": "hidden","height": "0px"},
id="corpus-select-menu",
children=[
html.Label(id="corpus-select-title", children="Corpus"),
corpus_element,
],
),
html.Div(
id="save-select-menu",
className='saves-select-menu',
children=[
html.Label(id="save-select-title", children="Analysis"),
html.Div(id="save-with-button",className="side-by-side",children=[saves_element,
html.Button("SAVE",id="save-analysis", n_clicks=0)]),
html.Div(id="save-pop-up",children=[])
],
),
html.Div(id="year-range",className="side-by-side",style={"margin-top":"5%","max-width":"96%"},
children=[
html.Label("From"),
daq.NumericInput(
id="year-from",
style={"color":"#e85e56"},
className="year-selector",
min=min(year_list),
max=max(year_list),
value= loaded["year"][0] if "year" in loaded else min(year_list)
),html.Label("To"),
daq.NumericInput(
id="year-to",
style={"color":"#e85e56"},
className="year-selector",
min=min(year_list),
max=max(year_list),
value=loaded["year"][1] if "year" in loaded else max(year_list)
),
]
),
html.Div(
id="query-select-menu-id",
className="query-select-menu",
children=[
html.Label(id="query-select-title", children="Query"),
html.Div(
className="side-by-side",style={"max-width":"95%"},
children=[
html.Label("Base Term"),
dcc.Input(id="base-term", className="dash-input", type="text", placeholder="input text...",
value=loaded["base"])
],
),
html.Label(id="add-terms", children="Add Related Words",style={"padding-top":"12px"}),
html.Div(
id="candidates",
className="side-side-side",
children=[
html.Div(
dcc.Checklist(
id={'type':'term','index':1},
options=[{"label": "[Not found]", "value": "[Not found]"}],
labelClassName="unselected-term",
),
),
]
),
html.Button("FORM A PHRASE",id="form-phrase"
),
html.Button("ADD A WORD",id="add-single"
),
html.Label(id="add-terms2", children="Words Added",style={"padding-top":"12px"}),
html.Div(id="added-terms", className="side-side-side2", children=[
html.Div(id="added-terms-fromside",children=added_option)
]
),
html.Label(children="Add Manually"),
html.Div(
className="side-by-side",
children=[
dcc.Input(id="manu-term", className="dash-input", type="text"),
html.Button("ADD",id="manu-add",style={"margin-left":"10px","width":"20%",
"line-height": "300%"}),
],
),
# hidden divs, record the selected terms
html.Div(id='added-terms-global', style={'display': 'none'},children=loaded["added"]
),
html.Div(id='added-terms-global-frompop', style={'display': 'none'},children=[]
)
]
)
],
)
# load saved selected analysis
def load_analysis(corpus_name,analysis_name):
if analysis_name == "create new":
return dict({"base":"","added":[],"groups":[]})
else:
with open(corpus[corpus_name]+"groups/"+analysis_name[2:-2], 'r') as file:
return json.loads(file.read())
# --- build saving menu ---
@app.callback(Output("save-pop-up", "children"),
[Input("save-analysis", 'n_clicks')],
[State("base-term", 'value'),
State("added-terms-global", "children"),
State("group-stored-data","data"),
State("year-from","value"),State("year-to","value")]
)
def generate_modal_for_save(n,base,added,groups,y_from,y_to):
if n>0:
group_divs=[]
if groups:
for g in range(0,len(groups[1])):
group_name = groups[1][g]
group_words = groups[0][g]
group_div=[]
for w in group_words:
group_div.append(html.Div(className="box-content2",children="_".join(w.split())))
group_all=groups[2][g]
if group_all == True:
box_class = "small-box-AND"
else:
box_class = "small-box-OR"
group_divs.append(html.Div(className=box_class,children=[
html.Div(className="box-title2",children=group_name),
html.Div(children=group_div)
]))
if len(added)>0:
word_add=added[0]
for q in added[1:]:
word_add+=", "
word_add+="_".join(q.split())
else:
word_add=[]
display_boxes = html.Div(className="box",children=[
html.Div(children=[
html.Div(className="box-title",children="Year Range"),
html.Div(className="box-content",children=html.Div(str(y_from)+" - "+str(y_to)))
]),
html.Div(children=[
html.Div(className="box-title",children="Base Term"),
html.Div(className="box-content",children=base)
]),
html.Div(children=[
html.Div(className="box-title",children="Words Added"),
html.Div(className="box-content",children=word_add)
]),
dcc.Loading(id='dowload-output',color="#e85e56",
children=[html.Div(style={"text-align":"right"},children=[html.Button("DOWNLOAD CORPUS",id="export-btn",style={
"width":"200px","margin-top":"30px","margin-bottom":"20px"})])]),
html.Div(children=[
html.Div(className="box-title",children="Groups"),
html.Div(className="box-group",children=group_divs)
])
])
return [html.Div(
id="markdown2",
style={"display": "block"},
className="modal",
children=(
html.Div(
id="markdown-container2",
className="markdown-container",
children=[
html.Div(
className="close-container",
children=html.Button(
"Close",
style={"width":"90px"},
id="markdown_close2",
n_clicks=0,
className="closeButton",
),
),display_boxes,
html.Div(
className="markdown-text-save",
children=[html.Div(id="saving",
className="side-by-side",
children=[
dcc.ConfirmDialog(id='confirm-replace',
message='Analysis name exists! Are you sure you want to replace it?',
),
html.Div(children="Analysis Name",style={"padding-top": "15px",
"padding-left": "25px","font-size": "9pt"}),
dcc.Input(id="save-name", className="dash-input", type="text"),
],
),
html.Div(style={"text-align":"right","margin-right":"30px"},children=[html.Button("SAVE THIS ANALYSIS",id="save-add",style={"width":"200px"})])]
),
]
))
)]
# save analysis
@app.callback(
[Output("confirm-replace","displayed"),Output("markdown2", "style"),Output("save-select-dropdown","options"),Output("save-select-dropdown","value")],
[Input("markdown_close2", "n_clicks"),Input("save-add", "n_clicks"),Input('confirm-replace', 'submit_n_clicks')],
[State("base-term", 'value'),State("added-terms-global", "children"),State("group-stored-data","data"),
State("save-name",'value'),State("corpus-select-dropdown","value"),
State("save-select-dropdown","options"),
State("save-select-dropdown","value"), State("year-from","value"),State("year-to","value")])
def update_click_output2(close_click,save_click,replace_click,base,added,
groups,name,corpus_name,options,save_name,y_from,y_to):
ctx = dash.callback_context
if ctx.triggered:
prop_id = ctx.triggered[0]["prop_id"].split(".")[0]
if (prop_id == "markdown_close2") & (close_click>0):
return [False,{"display": "none"},options,save_name]
if ((prop_id == "save-add") | (prop_id == "confirm-replace")):
saved={"base":base, "added":added, "groups":groups, "year":[y_from,y_to]}
saves_path=corpus[corpus_name]+"groups/"
savefiles = [f for f in listdir(saves_path) if isfile(join(saves_path, f))]
if name in savefiles:
if not replace_click:
return [True, {"display": "block"}, options,save_name]
options = save_analysis_write(corpus_name, name, saved, options)
return [False,{"display": "none"},options,"[ "+name+" ]"]
return [False,{"display": "block"},options,save_name]
def save_analysis_write(corpus_name, name, content, options):
with open(corpus[corpus_name]+"groups/"+name, 'w') as file:
file.write(json.dumps(content))
options.append({"label": "[ "+name+" ]", "value": "[ "+name+" ]"})
file.close()
return options
@app.callback(Output("dowload-output","children"),
[Input("export-btn","n_clicks")],
[State("corpus-select-dropdown","value"),State("base-term", 'value'),
State("added-terms-global", "children"),
State("year-from","value"),State("year-to","value")])
def export_corpus(n_clicks,corpus_name,t,added,y_from,y_to):
if n_clicks>0:
corpus_ind=corpus[corpus_name]
added.append(t)
for term in added: #handle phrases
if "_" in term:
added.append(term.replace("_"," "))
added.remove(term)
csv_string = preprocess_corpus.filter_corpus(corpus_ind, added, y_from, y_to)
csv_string = "data:text/csv;charset=utf-8,%EF%BB%BF" + urllib.parse.quote(csv_string)
ele=html.Div(style={"text-align":"right"},children=[html.A(
html.Button("Click to Download",style={
"width":"200px","margin-top":"30px","margin-bottom":"20px"}),
download="filtered_corpus.csv",href=csv_string,target="_blank"
)])
return [ele]
return [html.Div(style={"text-align":"right"},children=[html.Button("DOWNLOAD CORPUS",id="export-btn",style={
"width":"200px","margin-top":"30px","margin-bottom":"20px"})])]
# --- build "adding terms" menu ---
#find related terms
@app.callback(Output("candidates", "children"),
[Input("base-term", 'value'),Input("corpus-select-dropdown","value")],
[State("base-term", 'value')]
)
def displayClick(value, corpus_name,v):
if v:
term_list=[v]
if corpus_name:
# find top50 similar terms from word2vec
top_terms = word2vec.find_similar(corpus_name, term_list, 50)
i=0
option_list=[]
for term in top_terms:
i+=1
option_list.append(html.Div(dcc.Checklist(id={'type':'term','index':i},
options=[{"label": term[0], "value": term[0]}],
labelClassName="unselected-term",)
))
return option_list
@app.callback(Output({'type':'term', 'index':MATCH}, 'labelClassName'),
[Input({'type':'term', 'index':MATCH}, 'value')],
[State({'type':'term', 'index':MATCH}, 'labelClassName')])
def displayClick(value, labelClassName):
if not value:
return "unselected-term"
if labelClassName == "unselected-term":
return "selected-term"
else:
return "unselected-term"
# functions for adding terms (single and phrases)
@app.callback([Output("added-terms-fromside", "children"),
Output({'type':'term', 'index':ALL}, "value"),
Output("added-terms-global", "children"),
Output("manu-term","value")
],
[Input("add-single", 'n_clicks'),
Input("form-phrase", 'n_clicks'),
Input({'type':'selected', 'index':ALL}, 'value'),
Input("added-terms-global-frompop", "children"),
Input("manu-add", "n_clicks")
],
[State({'type':'term', 'index':ALL}, 'value'),
State("added-terms-fromside", "children"),
State("added-terms-global", "children"),
State("manu-term", "value"),
]
)
def add_terms(single_click,phrase_click,removes,add_from_pop,manu_click,
values,added_value, added_value_global,manu_term):
options=added_value;
empty_list=[]
for (i, value) in enumerate(removes):
if value:
for x in range(0,len(values)):
empty_list.append([])
if value[0] in added_value_global:
added_value_global.remove(value[0])
for selected_i in options:
if selected_i['props']['children'][0]['props']['options'][0]['value']==value[0]:
options.remove(selected_i)
return [options, empty_list, added_value_global,""]
ctx = dash.callback_context
if not ctx.triggered:
button_id = 'add-single' # default
else:
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if ((button_id == "add-single") | (button_id== "added-terms-global-frompop") | (button_id == "manu-add")):
for (i, value) in enumerate(values):
if value:
if ((len(value)>=1)&(button_id == "add-single")):
if not value[0] in added_value_global: #check repeated adding
options.append(html.Div([dcc.Checklist(
id={'type':'selected','index':i},
options=[{'label': value[0], 'value': value[0]}],
labelClassName="selected-term2"
)]
)),
added_value_global.append(" ".join(value[0].split('_'))) #update term list
empty_list.append([]) #reset term style to "unchecked"
if (button_id== "added-terms-global-frompop"):
i=0
for value in add_from_pop:
if value:
if not value in added_value_global: #check repeated adding
options.append(html.Div([dcc.Checklist(
id={'type':'selected','index':'new_'+str(i)},
options=[{'label': "_".join(value.split()), 'value': value}],
labelClassName="selected-term2"
)]
))
added_value_global.append(value) #update term list
i+=1
if (button_id == "manu-add"):
manu_term=re.sub(r'[^a-zA-Z0-9 ]', ' ', manu_term)
if not manu_term in added_value_global: #check repeated adding
options.append(html.Div([dcc.Checklist(
id={'type':'selected','index':"manu_"+str(len(added_value_global))},
options=[{'label': "_".join(manu_term.split()), 'value': manu_term}],
labelClassName="selected-term2"
)]
)),
added_value_global.append(manu_term)
elif button_id == "form-phrase":
phrase=""
for (i, value) in enumerate(values):
if value:
if len(value)>=1:
phrase+=value[0]
phrase+=" "
empty_list.append([]) #reset term style to "unchecked"
phrase=phrase[:-1]
phrase_len=len(phrase.split())
if phrase_len>=2:
if not phrase in added_value_global: #check repeated adding
options.append(html.Div([dcc.Checklist(
id={'type':'selected','index':i*10},
options=[{'label': "_".join(phrase.split()), 'value': phrase}],
labelClassName="selected-term2"
)]
))
added_value_global.append(phrase) #update term list
return [options, empty_list, added_value_global,""]
# --- build tabs (right window) ---
def build_tabs():
return html.Div(
id="tabs",
className="tabs",
children=[
dcc.Tabs(
id="app-tabs",
value="tab00",
className="custom-tabs",
children=[
dcc.Tab(
id="Overview-tab",
label="Overview",
value="tab00",
className="custom-tab",
selected_className="custom-tab--selected",
),
dcc.Tab(
id="Specs-tab",
label="Sentences",
value="tab1",
className="custom-tab",
selected_className="custom-tab--selected",
),
dcc.Tab(
id="Group-tab",
label="Grouping",
value="tab22",
className="custom-tab",
selected_className="custom-tab--selected",
),
dcc.Tab(
id="Graph-tab",
label="Graphs",
value="tab3",
className="custom-tab",
selected_className="custom-tab--selected",
),
],
)
],
)
# --- build "sentences" tab ---
# search, and show ranking
def build_tab_1(corpus_name):
corpus_ind_dir=corpus[corpus_name]
display_fileds = preprocess_corpus.get_table_fieldnames(corpus_ind_dir)
display_fileds.append("score")
opt=[{'label': f.upper(), 'value': f} for f in display_fileds]
return [
dcc.Store(id='memory-output'),
dcc.Loading(color="rgba(240, 218, 209,0.8)",type="cube",style={"padding-top":"25%"},children=[
html.Div(style={"margin-left": "30px","margin-top": "1.5%", "font-variant": "all-small-caps","color": "#e85e56"},
children="QUERY"),
html.Div(id="current_query",style={"margin-left": "50px", "color": "#f4e9dc","width": "42%"},
children=""),
html.Div(style={"display":"flex"},children=[
html.Div(style={"width": "430px"},
children=[html.Div(style={"margin-left": "30px", "font-variant": "all-small-caps","color": "#e85e56"},
children="DISPLAYED COLUMNS"),
dcc.Dropdown(id="r_table_paras",className="table-dropdown",style={"margin-left":"10%"},
options=opt,value=display_fileds,multi=True)]
),
html.Div(children=[html.Div(style={"font-variant": "all-small-caps","color": "#e85e56"},
children="SENTS PER PAGE"),
daq.NumericInput(id="n_pp",style={"margin-top": "4px","margin-left": "10%","color":"#f4e9dc","width": "40%"},
className="year-selector sent-pp",min=10,max=1000,value=16)]
)
]),
html.Div(
id="rel_sent",style={"position": "absolute","right": "1.5%","top": "90px","font-variant": "all-small-caps"},className="side-by-side",
children=[""]
),
html.Div(
id="ranking-table",style={"margin-top":"1%"},
className="output-datatable"
),
]),
html.Div(
id="full-sentence-pop-up",
children=[
]
)
]
@app.callback([Output("ranking-table", "children"),Output('memory-output', 'data'),
Output("rel_sent","children"),Output("current_query","children")],
[Input("base-term", 'value'),Input("corpus-select-dropdown","value"),
Input("added-terms-global", "children"),Input("year-from","value"),Input("year-to","value"),
Input("r_table_paras",'value'),Input("n_pp","value")],
[State("base-term", 'value'),
State('memory-output', 'data'),State("rel_sent","children"),State("current_query","children")]
)
def show_ranking(base_term,corpus_name,added,y_from,y_to,cols,npp,t, mo_result,rs,cq):
if corpus_name:
corpus_ind = corpus[corpus_name]
if base_term:
added.append(t) #add base term
if y_from > y_to:
return [html.Div("Please correct the year range."),"","",""]
for term in added: #handle phrases
if "_" in term:
added.append(term.replace("_"," "))
added.remove(term)
ctx = dash.callback_context
if not ctx.triggered:
button_id = '' # default
else:
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if ((button_id == "r_table_paras")|(button_id == "n_pp")): # no need to search index again, just change layout
result = mo_result[0]
tooltip = mo_result[1]
if len(result)>0:
result_df = pd.DataFrame.from_records(result)
columns_d = [{"id": "id", "name": "id"}]
columns_d.append({"id": "sentence", "name": "sentence"})
for c in result_df.columns:
if ((c != "id")&(c != "sentence")&(c in cols)):
columns_d.append({"id": c, "name": c})
return [build_ranking_table(result,columns_d,tooltip,npp),
mo_result,rs,cq]
else:
return [html.Div("No result"),mo_result,rs,cq]
else: # need to search the index
result, tooltip, rel_sent_no, sent_no, rel_article_no, article_no=preprocess_corpus.search_corpus(corpus_ind, added, y_from, y_to)
result_df = pd.DataFrame.from_records(result)
del result_df["document"]
rel_sent_div=[ html.Div(className="number-card-1",children=[
html.Div(className="number-back",children=[
html.Div(className="number-dis",children=[rel_sent_no]),
html.Div(className="number-label",children=[html.Div("RELEVANT SENTENCES")]),
]),html.Div("|",className="saperator"),
html.Div(className="number-back",children=[
html.Div(className="number-dis2",children=[sent_no]),
html.Div(className="number-label2",children=[html.Div("TOTAL SENTENCES")]),
])
]),
html.Div(className="number-card-2",children=[
html.Div(className="number-back",children=[
html.Div(className="number-dis",children=[rel_article_no]),
html.Div(className="number-label",children=[html.Div("RELEVANT DOCUMENTS")]),
]),html.Div("|",className="saperator"),
html.Div(className="number-back",children=[
html.Div(className="number-dis2",children=[article_no]),
html.Div(className="number-label2",children=[html.Div("TOTAL DOCUMENTS")]),
])
])
]
if len(result)>0:
columns_d = [{"id": "id", "name": "id"}]
columns_d.append({"id": "sentence", "name": "sentence"})
for c in result_df.columns:
if ((c != "id")&(c != "sentence")&(c in cols)):
columns_d.append({"id": c, "name": c})
return [build_ranking_table(result,columns_d,tooltip,npp), [result,tooltip], rel_sent_div," | ".join(added)]
else:
return [html.Div("No result"),"",""," | ".join(added)]
else:
return [html.Div("Please type in the base term in the left pane"),"","",""]
else:
return [html.Div("Start by selecting a corpus"),"","",""]
def build_ranking_table(result,columns_d,tooltip,npp):
return dash_table.DataTable(
id="ranking_table",
sort_action='native',
sort_mode='multi',
filter_action="native",
style_header={"fontWeight": "bold", "color": "inherit","border-bottom":"1px dashed"},
style_as_list_view=True,
fill_width=True,
page_size=npp,
style_cell_conditional=[
{"if": {"column_id": "sentence"}, 'width': '500px',"maxWidth":'500px'},
{"if": {"column_id": "title"}, "padding-left":"15px","maxWidth":'300px'},
{'if': {'column_id': 'author'},'maxWidth': '150px'},
{'if': {'row_index': 'odd'},"backgroundColor":"#49494966"}
],
style_cell={
"backgroundColor": "transparent",
"fontFamily": "Open Sans",
"padding": "0 0.2rem",
"color": "#f4e9dc",
"border": "none",
'overflow': 'hidden',
'textOverflow': 'ellipsis',
'width': '55px',
'minWidth': '55px',
'maxWidth': '200px',
"padding-left":"10px",
"textAlign": "left"
},
css=[
#{"selector": ".dash-cell.focused","rule": "background-color: #f4e9dc !important; border:none;"},
{"selector": "table", "rule": "--accent: #e85e56;"},
{"selector": "tr:hover td", "rule": "color: #e85e56 !important; background-color:transparent !important; cursor:pointer;height:10px;"},
{"selector": "td:hover", "rule": "border-bottom: dashed 0px !important;"},
{"selector": ".dash-spreadsheet-container table",
"rule": '--text-color: #e85e56 !important'},
{"selector":".previous-next-container","rule":"float: left;"},
{"selector": "tr", "rule": "background-color: transparent;"},
{"selector": ".current-page", "rule": "background-color: transparent;"},
{"selector":".current-page::placeholder","rule":"color:#e85e56;"},
{"selector": ".column-header--sort","rule":"color: #e85e56; padding-right:3px;"}
],
style_data_conditional=[
{"if": {"state": "active"}, # 'active' | 'selected'
"border": "0px solid"}]+
data_bars(result, 'score'),
data=result,
columns=columns_d,
tooltip_data=tooltip,
tooltip_delay=1000, #1s
tooltip_duration=None,
selected_rows=[]
)
def data_bars(df, column):
Scores=[]
for r in df:
Scores.append(r[column])
n_bins = 100
bounds = [i * (1.0 / n_bins) for i in range(n_bins + 1)]
ranges = [
((max(Scores) - min(Scores)) * i) + min(Scores)
for i in bounds
]
styles = []
for i in range(1, len(bounds)):
min_bound = ranges[i - 1]
max_bound = ranges[i]
max_bound_percentage = bounds[i] * 100
styles.append({
'if': {
'filter_query': (
'{{{column}}} >= {min_bound}' +
(' && {{{column}}} < {max_bound}' if (i < len(bounds) - 1) else '')
).format(column=column, min_bound=min_bound, max_bound=max_bound),
'column_id': column
},
'background': (
"""
linear-gradient(90deg,
#f4e9dc 0%,
#f4e9dc {max_bound_percentage}%,
#1E1C24 {max_bound_percentage}%,
#1E1C24 100%)
""".format(max_bound_percentage=max_bound_percentage)
),
'paddingBottom': 2,
'paddingTop': 2,
'border-bottom': "1px dashed #1e1c24",
'color':'#494949'
})
return styles
# pop-up window
@app.callback(
[Output("full-sentence-pop-up", "children")],
[Input('ranking_table', 'active_cell')],
[State('memory-output', 'data')])
def update_graphs(active_cell,data):
if active_cell:
for i in data[0]:
if i['id'] == active_cell['row_id']:
return generate_modal(i['document'])
raise PreventUpdate
# term selection in the sentence pop up window
@app.callback(
Output("markdown", "style"),[Input("markdown_close", "n_clicks")])
def update_click_output(close_click):
ctx = dash.callback_context
if ctx.triggered:
prop_id = ctx.triggered[0]["prop_id"].split(".")[0]
if prop_id == "markdown_close":
return {"display": "none"}
return {"display": "block"}
@app.callback(Output({'type':'sent_term', 'index':MATCH}, 'labelClassName'),
[Input({'type':'sent_term', 'index':MATCH}, 'value')],
[State({'type':'sent_term', 'index':MATCH}, 'labelClassName')])
def displayClick(value, labelClassName):
if not value:
return "unselected-sent-term"
if labelClassName == "unselected-sent-term":
return "selected-sent-term"
else:
return "unselected-sent-term"
# build modal (pop up window)
def generate_modal(text=""):
word_list = text.split()
option_list=[]
i=0
for term in word_list:
option_list.append(html.Div(dcc.Checklist(id={'type':'sent_term','index':i},
options=[{"label": term, "value": term}],
labelClassName="unselected-sent-term",)
))
i+=1
return [html.Div(
id="markdown",
style={"display": "block"},
className="modal",
children=(
html.Div(
id="markdown-container",
className="markdown-container",
children=[
html.Div(
className="close-container",
children=html.Button(
"Close",
id="markdown_close",
n_clicks=0,
className="closeButton",
),
),
html.Div(
className="markdown-text",id="pop-up-sent",
children=option_list
),html.Br(),
html.Button("Check Frequency",
id="check_sf",n_clicks=0
),html.Button("ADD TO THE QUERY",style={"margin-left":"20px"},
id="add-to-query",n_clicks=0
),
html.Br(),html.Br(),
html.Div(
id="sf_result_container",
children=[dash_table.DataTable(
id='sf_result11',
sort_action='native',
sort_mode='multi',
columns=[{"id": c, "name": c} for c in ["Term","Frequency"]],
style_cell_conditional=[
{"if": {"column_id": "Term"}, "textAlign": "left"},
{"if": {"state": "active"}, "border": "0px solid"}
],
style_cell={
"backgroundColor": "#494949","fontFamily": "Open Sans","padding": "0 2rem",
"color": "f4e9dc","border": "none",'overflow': 'hidden','textOverflow': 'ellipsis',
},
css=[
{"selector": "tr:hover td", "rule": "color: #e85e56 !important;"},
{"selector": "td", "rule": "border-bottom: dashed 1px !important;"},
{"selector": ".dash-cell.focused",
"rule": "background-color: #494949 !important;"},
{"selector": ".dash-spreadsheet-container table",
"rule": '--text-color: #f4e9dc !important'},
{"selector": "table", "rule": "--accent: #f4e9dc;"},
{"selector": "tr", "rule": "background-color: transparent"},
{"selector": ".column-header--sort","rule":"color: #e85e56; padding-right:3px;"}
],
data=[{"Term":"Please select...","Frequency":""}])]
)
],
)
),
)]
# add terms from the pop up window
@app.callback([Output({'type':'sent_term', 'index':ALL}, "value"),
Output("added-terms-global-frompop", "children")
],
[Input("add-to-query", 'n_clicks')],
[State({'type':'sent_term', 'index':ALL}, 'value'),
State("added-terms-global", "children")]
)
def add_from_pop(n_clicks,values,added_value_global):
empty_list=[]
new_add=[]
ctx = dash.callback_context
if not ctx.triggered:
button_id = 'add-to-query' # default
else:
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id == "add-to-query":
phrase=""
for (i, value) in enumerate(values):
if value:
if len(value)>=1:
phrase+=re.sub(r'[^a-zA-Z0-9_]', '', value[0])
phrase+=" "
empty_list.append([]) #reset term style to "unchecked"
phrase=phrase[:-1]
phrase_len=len(phrase.split())
if phrase_len>=1:
if not phrase in added_value_global:
new_add.append(phrase)
if n_clicks>0:
return [empty_list,new_add]
else:
raise PreventUpdate
# function for checking sentence frequency
@app.callback([Output("sf_result_container", "children")],
[Input("check_sf", 'n_clicks')],
[State({'type':'sent_term', 'index':ALL}, 'value'),
State("corpus-select-dropdown","value"),State("sf_result11","data")]
)
def return_sf(n_clicks,values,corpus_name,tabledata):
if n_clicks>0:
query=""
for (i, value) in enumerate(values):
if value:
if len(value)>=1:
if len(query)>0:
query+=" "
query+=value[0]
corpus_ind = corpus[corpus_name]
(query, sf)=preprocess_corpus.check_sf(corpus_ind, [query])
if n_clicks>1:
tabledata.append({"Term":query[0],"Frequency":str(sf[0])})
else:
tabledata=[{"Term":query[0],"Frequency":str(sf[0])}]
return [dash_table.DataTable(
id='sf_result11',
sort_action='native',
sort_mode='multi',
row_deletable=True,
columns=[{"id": c, "name": c} for c in ["Term","Frequency"]],
style_cell_conditional=[
{"if": {"column_id": "Term"}, "textAlign": "left"},
{"if": {"state": "active"}, "border": "0px solid"}
],
style_cell={
"backgroundColor": "#494949",
"fontFamily": "Open Sans",
"padding": "0 2rem",
"color": "#f4e9dc",
"border": "none",
'overflow': 'hidden',
'textOverflow': 'ellipsis',
},
css=[
{"selector": "tr:hover td", "rule": "color: #e85e56 !important;"},
{"selector": "td", "rule": "border-bottom: dashed 1px !important;"},
{"selector": ".dash-cell.focused",
"rule": "background-color: #494949 !important;"},
{"selector": ".dash-spreadsheet-container table",
"rule": '--text-color: #91dfd2 !important'},
{"selector": "table", "rule": "--accent: #f4e9dc;"},
{"selector": "tr", "rule": "background-color: transparent"},
{"selector": ".column-header--sort","rule":"color: #e85e56; padding-right:3px;"}
],
data=tabledata
)]
else:
return [dash_table.DataTable(
id='sf_result11',
sort_action='native',
sort_mode='multi',
columns=[{"id": c, "name": c} for c in ["Term","Frequency"]],
style_cell_conditional=[
{"if": {"column_id": "Term"}, "textAlign": "left"},
{"if": {"state": "active"}, "border": "0px solid"}
],
style_cell={
"backgroundColor": "#494949",
"fontFamily": "Open Sans",
"padding": "0 2rem",
"color": "#f4e9dc",
"border": "none",
'overflow': 'hidden',