-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
1278 lines (1094 loc) · 47 KB
/
app.py
File metadata and controls
1278 lines (1094 loc) · 47 KB
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
# sidebar.py
import dash
from dash import dcc
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import pandas as pd
from dash import Input, Output, State, ALL, MATCH
import warnings
import logging
from dash.exceptions import PreventUpdate
#import dash_auth
from flask import request
import sqlalchemy
import sys
from elasticsearch import Elasticsearch
from urllib.parse import urlparse, parse_qs
import os
import base64
import dataIO
import structures as struct
import time
######################################################################################
app = dash.Dash(
__name__,
external_stylesheets=["custom.css", dbc.icons.BOOTSTRAP ],
routing_callback_inputs={
# The app state is serialised in the URL hash without refreshing the page
# This URL can be copied and then parsed on page load
"state": State("main-url", "hash"),
},
)
app.title = "UK LLC Explore"
server = app.server
app._favicon = ("assets/favicon.ico")
# google analytics:
app.index_string = """<!DOCTYPE html>
<html>
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-T6G5RKPQ2F"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-T6G5RKPQ2F');
</script>
{%metas%}
<title>{%title%}</title>
{%favicon%}
{%css%}
</head>
<body>
{%app_entry%}
<footer>
{%config%}
{%scripts%}
{%renderer%}
</footer>
</body>
</html>"""
def searchbox_connect():
url = urlparse(os.environ['SEARCHBOX_URL'])
######## test
es = Elasticsearch(
[os.environ['SEARCHBOX_URL']],
http_auth=(url.username, url.password)
)
return es
######################################################################################
### Data prep functions
es = searchbox_connect()
########## Load data from API and prepare for use in app
datasets_df = dataIO.get_datasets()
dataset_counts = datasets_df[["source", "table", "participants_included", "participant_count", "Type"]]
source_info = dataIO.get_sources()
spine = datasets_df[["source", "table"]].drop_duplicates(subset = ["source", "table"])
map_data = dataIO.get_region_counts()
gj = dataIO.load_geojson()
themes = []
for x in list(set(source_info["Themes"])):
themes += x.split(",")
for y in list(set(datasets_df["topic_tags"].fillna(""))):
themes += y.split(",")
for i in range(len(themes)):
themes[i] = themes[i].replace("\n", "")
themes[i] = themes[i].strip()
themes = list(set(themes))
themes = sorted(themes, key=str.casefold)
themes.remove("")
def prep_counts(df):
'''
apply function
'''
if df["count"] == "<10":
return 10
elif pd.isna(df["count"]):
return 0
return int(df["count"])
def load_or_fetch_map(study):
df1 = map_data.loc[map_data["source"] == study]
df1 = df1.drop(["source"], axis=1)
df2 = pd.DataFrame([[ str(x), y] for x, y in zip(df1.columns, df1.iloc[0].values) ], columns = ["RGN23NM", "count"])
df2["labels"] = df2["count"]
df2["labels"].fillna("Not available")
df2["count"] = df2.apply(prep_counts, axis = 1)
return df2
######################################################################################
######################################################################################
### page asset templates
# Titlebar ###########################################################################
titlebar = struct.main_titlebar(app, "UK LLC Data Discovery Portal")
# Left Sidebar #######################################################################
sidebar_catalogue = struct.make_sidebar_catalogue(datasets_df)
sidebar_title = struct.make_sidebar_title()
sidebar_left = struct.make_sidebar_left(sidebar_title, sidebar_catalogue)
# Body ################################################################################
maindiv = struct.make_body(sidebar_left, app, spine, themes)
# Main div template ##################################################################
schema_record = struct.make_variable_div("active_source")
table_record = struct.make_variable_div("active_dataset")
current_tab = struct.make_variable_div("current_tab")
selected_tables = struct.make_variable_div("selected_tables")
shopping_basket_op = struct.make_variable_div("shopping_basket", [])
open_schemas = struct.make_variable_div("open_schemas", [])
user = struct.make_variable_div("user", None)
save_clicks = struct.make_variable_div("save_clicks", 0)
placeholder = struct.make_variable_div("placeholder", "placeholder")
account_section = struct.make_account_section()
hidden_body = struct.make_hidden_body(source_info, dataset_counts)
# Variable Divs ####################################################################
###########################################
### Layout
app.layout = struct.make_app_layout(titlebar, maindiv, account_section, [schema_record, table_record, current_tab, shopping_basket_op, open_schemas, hidden_body, user, save_clicks, placeholder], dcc.Location(id='url', refresh=False),)
print("---------------------\nBuilt app layout\n----------------------")
###########################################
### Actions
###########################################
'''
### Login
@app.callback(
Output('user', "data"),
Input('account_dropdown','n_clicks'),
prevent_initial_call=True
)
def login(_):
print("auth placeholder - do flask or ditch")
'''
### Update titles #########################
#########################
### DOCUMENTATION BOX #####################
'''
efficiency:
approx 995/try all in
'''
@app.callback(
Output("source_category", "children"), # Source_ type
Output("study_title", "children"), # Source_name
Output('source_description_div', "children"), # Aims
Output("study_summary", "children"), # several variables
Output("study_table_div", "children"), # list of datasets in source
Output('source_row', "style"), # style, for hiding/showing body
Input('active_source','data'),
#prevent_initial_call = True
)
def update_schema_description(source):
'''
When schema updates, update documentation
'''
print("Updating schema page text, schema = '{}'".format(source))
if source != None and source != "None":
info = source_info.loc[source_info["source"] == source]
### title ####
source_name = info["source_name"].values[0]
if info["Type"].values[0] == "Linked":
title_text1 = "Linked Source"
elif info["Type"].values[0] == "LPS":
title_text1 = "LPS Source"
elif info["Type"].values[0] == "UK LLC Managed":
title_text1 = "UK LLC Managed Source"
else:
title_text1 = "UK LLC Data Source"
return title_text1, source_name, info["Aims"], struct.make_schema_description(info), struct.make_blocks_table(datasets_df.loc[datasets_df["source"]==source]), {"display": "flex"}
else:
#print(all_query)
r = es.search(index="index_spine", body={"query" : {"match_all" : {}}}, size = 1000)
search_results = []
for hit in r["hits"]["hits"]:
search_results.append({key: hit["_source"][key] for key in ["source", "source_name", "Aims"]})
if len(search_results) >0:
info = pd.DataFrame(search_results).drop_duplicates(subset=["source"])
search_results = struct.sources_list(app, info, "main_search")
else:
search_results = struct.error_p("No data available")
return "UK LLC Data Sources", "Browse and select a source for more information", "", "", search_results, {"display": "none"}
@app.callback(
Output('Map', "children"),
Input("current_tab", "data"),
Input('active_source','data'),
prevent_initial_call=True
)
def update_schema_map(current_tab, source):
'''
When schema updates, update documentation
'''
print("Updating schema map, schema = '{}'".format(source))
trigger = dash.ctx.triggered_id
print(" boxplot trigger {}".format(trigger))
if source != None and source != "None":
### map #####
t0 = time.time()
try:
data = load_or_fetch_map(source)
if sum(data["count"]) == 0:
map = struct.error_p("Coverage is not available for {}".format(source))
else:
map = struct.choropleth(data, gj)
except:
data = None
map = struct.error_p("Error loading map")
print("Error: failed to load map data")
maptime = time.time() - t0
print("maptime", round(maptime, 3))
return map
else:
return None
@app.callback(
Output('source_linkage_graph', "children"),
Input("current_tab", "data"),
Input('active_source','data'),
prevent_initial_call=True
)
def update_schema_hbar(current_tab, source):
'''
When schema updates, update documentation
'''
print("Updating schema hbar, schema = '{}'".format(source))
trigger = dash.ctx.triggered_id
print(" hbar trigger {}".format(trigger))
if source != None and source != "None":
data = dataIO.get_source_linkage_rate(source = source)
expected_labels = [
"NHS England",
"Place - household level",
"Place - postcode level",
"Place - small area level"
]
# initialise defaults
label_map = {k: {"value": 0, "count": 0} for k in expected_labels}
# ONLY touch data if columns exist
if (
data is not None
and hasattr(data, "columns")
and all(col in data.columns for col in ["perc", "group", "count"])
):
for _, row in data.iterrows():
l = str(row["group"]).replace("]","").replace("[","").replace("'","")
l = l.replace("NHS_linkage","NHS England")
if l in label_map:
label_map[l] = {
"value": round(row["perc"], 2),
"count": row["count"]
}
# rebuild arrays (always runs)
labels = expected_labels
values = [label_map[l]["value"] for l in labels]
counts = [label_map[l]["count"] for l in labels]
if len(labels) > 0 and source not in ("NHSE", "UKLLC"):
try:
hbar = struct.hbar(labels, values, counts)
except Exception as e:
print("HBAR ERROR:", e)
raise
else:
hbar = struct.error_p("Linkage statistics are not currently available for {}".format(source))
return hbar
else:
return ""
@app.callback(
Output('source_age_graph', "children"),
Input("current_tab", "data"),
Input('active_source','data'),
prevent_initial_call=True
)
def update_schema_boxplot(current_tab, source):
'''
When schema updates, update documentation
'''
print("Updating schema boxplot, schema = '{}'".format(source))
trigger = dash.ctx.triggered_id
'''
if trigger == "active_source" and current_tab != "source":
print("preventing update of boxplot")
raise PreventUpdate
'''
if trigger == None:
return struct.error_p("Nothing")
print(" boxplot trigger {}".format(trigger))
if source != None and source != "None":
ages = dataIO.get_source_age(source)
### boxplot #####
if len(ages["mean_age"].values) > 0:
try:
print("Confirm made boxplot")
boxplot = struct.boxplot(mean = ages["mean_age"], median = ages["q2_age"],
q1 = ages["q1_age"], q3 = ages["q3_age"],
lf = ages["lower_fence_age"], uf = ages["upper_fence_age"])
except Exception as e:
print(e)
boxplot = struct.error_p("Error: unable to make age boxplot")
else:
boxplot = struct.error_p("Age distribution statistics are not currently available for {}".format(source))
return boxplot
else:
return ""
### Dataset BOX #####################
@app.callback(
Output('dataset_description_div', "children"), # description text
Output('dataset_summary', "children"), # variables
Output('dataset_linkage_graph', "children"),
Output("dataset_age_graph", "children"),
Output('dataset_variables_div', "children"),
Output("dataset_header", "children"),
Output("dataset_title", "children"),
Output("dataset_row" , "style"),
Input('active_dataset', 'data'),
prevent_initial_update = True
)
def update_table_data(table_id):
'''
When table updates
with current schema
load table metadata (but not the metadata itself)
'''
trigger = dash.ctx.triggered_id
print("CALLBACK: Dataset BOX - updating table description with table {}, {}".format(table_id, trigger))
#pass until metadata block ready
if table_id != None and table_id != "None" and trigger:
table_split = table_id.split("-")
schema = table_split[0]
table = table_split[1]
blocks = datasets_df.loc[(datasets_df["source"] == schema) & (datasets_df["table"] == table)]
long_desc = blocks["long_desc"].values[0]
long_name = blocks["table_name"].values[0]
if blocks["Type"].values[0] == "Linked":
title_text1 = "Linked Source"
elif blocks["Type"].values[0] == "LPS":
title_text1 = "LPS Source"
elif blocks["Type"].values[0] == "UK LLC Managed":
title_text1 = "UK LLC Managed Source"
else:
title_text1 = "UK LLC Data Source"
if long_name and len(long_name) > 0:
title_text2 = str(long_name)
else:
title_text2 = str(schema) + " " + str(table)
blocks = blocks[["table_name", "collection_start", "collection_end", "participants_invited", "participants_included", "topic_tags", "links", 'special_conditions',"covid_only"]]
metadata_df = dataIO.get_labels(table_id)
data = dataIO.get_dataset_linkage_rate(source=schema, table_name=table)
ages = dataIO.get_dataset_age(source_name=schema, dataset_name=table)
labels = []
values = []
counts = []
if (
data is not None
and hasattr(data, "columns")
and all(col in data.columns for col in ["perc", "group", "count"])
):
for v, l, d in zip(data["perc"], data["group"], data["count"]):
l = str(l).replace("]","").replace("[","").replace("'","")
labels.append(l)
values.append(round(v, 2))
counts.append(str(d))
if len(labels) > 0 and schema not in ("NHSE", "UKLLC"):
hbar = struct.hbar(labels, values, counts)
elif schema in ("NHSE", "UKLLC"):
hbar = "Linkage statistics not available for {} {}".format(schema, table)
else:
hbar = "Linkage statistics are not currently available for {} {}".format(schema, table)
if len(ages["mean_age"].values) > 0:
boxplot = struct.boxplot(mean = ages["mean_age"], median = ages["q2_age"],
q1 = ages["q1_age"], q3 = ages["q3_age"],
lf = ages["lower_fence_age"], uf = ages["upper_fence_age"])
else:
boxplot = "Age distribution statistics are not currently available for {} {}".format(schema, table)
harmony_link = struct.create_harmony_link(metadata_df, title_text1 + " / " + title_text2 + " (imported from UKLLC)")
block_description = struct.make_block_description(blocks, harmony_link)
return long_desc, block_description, hbar, boxplot, struct.make_table(metadata_df, "block_metadata_table","dataset_info_table"), title_text1, title_text2, {"display": "flex"}
else:
dataset_table = datasets_df[["source", "table", "short_desc"]].rename(columns = {"source":"Source", "table":"Dataset", "short_desc":"Description"})
search_results_table = struct.make_table(dataset_table, "search_metadata_table", "none_selected")
return "", "", "", "", search_results_table, "UK LLC Datasets", "Browse and select a source for more information", {"display": "none"}
### BASKET REVIEW #############
@app.callback(
Output("basket_review_table_div", "children"),
Output("basket_review_text_div", "children"),
Output("basket_review_table_div", "style"),
Output("basket_review_text_div", "style"),
Input("shopping_basket", "data"),
)
def basket_review(shopping_basket):
'''
When the shopping basket updates
Update the basket review table
'''
trigger = dash.ctx.triggered_id
if trigger == None:
pass
#raise PreventUpdate
print("CALLBACK: Updating basket review table, trigger {}".format(trigger))
rows = []
df = datasets_df
for table_id in shopping_basket:
table_split = table_id.split("-")
source, table = table_split[0], table_split[1]
df1 = df.loc[(df["source"] == source) & (df["table"] == table)]
try: # NOTE TEMP LINKED OVERRIDE
#print(df1.columns)
row = [source, table, df1["short_desc"].values[0]]
except IndexError:
row = [source, table,""]
rows.append(row)
df = pd.DataFrame(rows, columns=["source", "table", "long_desc"])
brtable = struct.basket_review_table(df)
#always_available_tables = struct.always_available_table(ap_df)
if len(df) > 0:
return brtable, "You have {} datasets in your selection".format(len(df)), {"display":"flex"}, {"display":"none"}
else:
return brtable, struct.text_block("You currently have no additional datasets in your selection. Use the checkboxes in the UK LLC Data Catalogue sidebar to add datasets."), {"display":"none"}, {"display":"flex"}
#########################
@app.callback(
Output("body_content", "children"),
Output("hidden_body","children"),
Output("current_tab", "data"),
#Input("about", "n_clicks"),
Input("search", "n_clicks"),
#Input("d_overview", "n_clicks"),
Input("dd_source", "n_clicks"),
Input("dd_dataset", "n_clicks"),
Input('source_description_div', "children"), # When the dataset page is updated (means active source has changed and pages have updated)
Input('dataset_description_div', "children"), # When the dataset page is updated (means active table has changed and pages have updated)
Input("search2", "n_clicks"),
#Input("overview2", "n_clicks"),
Input("source2", "n_clicks"),
Input("dataset2", "n_clicks"),
Input('url', 'href'),
State("active_source", "data"),
State("active_dataset", "data"),
State("body_content", "children"),
State("hidden_body","children"),
State("current_tab", "data"),
prevent_initial_call=True
)
def body_sections(search, dd_source, dd_data_block, _, __, search2, source2, dataset2, href, schema_change, table_change, active_body, hidden_body, current_state):#, shopping_basket):
'''
When the tab changes
Read the current body
Read the hidden body
Update the body
Update the hidden body
Overhaul 17/10/2023:
Change the nav bar to a series of drop down menus and buttons
Body sections listens for all of these buttons
determine cause by looking at context
change the body accordingly
get id of sections.
'''
trigger = dash.ctx.triggered_id
print("Debug body trigger", trigger, "schema", schema_change, "table", table_change)
if trigger=="url":
# Parse the URL and extract query parameters
parsed_url = urlparse(href)
params = parse_qs(parsed_url.query)
input_value = params.get('source', [''])
print(href)
print("DEBUG input val", input_value)
if len(input_value) > 0 and input_value != "" and input_value != [""]:
schema_change = input_value
trigger = "dd_source"
print("read source from url", input_value)
else:
print("No url, preventing update")
raise PreventUpdate
print("DEBUG in url branch of body sections")
if (schema_change == None or schema_change == "None") and trigger == "source_description_div" : raise PreventUpdate
if trigger == "source_description_div" and current_state == "source": raise PreventUpdate
if (table_change == None or table_change == "None") and trigger == "dataset_description_div" : raise PreventUpdate
print("CALLBACK: body sections, activating", trigger)
if trigger == "active_source" or trigger == "active_dataset":
active_tab = active_body[0]["props"]["id"].replace("body_","").replace("dd_", "")
sections_states = {}
for section in active_body + hidden_body:
section_id = section["props"]["id"].replace("body_","").replace("dd_", "")
sections_states[section_id] = section
#print(sections_states)
a_tab_is_active = False
sections = ["search",
"source",
"dataset"]
active = []
inactive = []
for section in sections:
if section in trigger:
active.append(section)
a_tab_is_active = True
else:
inactive.append(section)
# Check: if no tabs are active, run search page
if not a_tab_is_active:
print("branch 1")
return [sections_states["search"], struct.footer(app)], [sections_states[s_id] for s_id in inactive], "search"
else:
print("branch 2")
return [sections_states[s_id] for s_id in active] + [ struct.footer(app)], [sections_states[s_id] for s_id in inactive], active[0]
@app.callback(
Output("offcanvas_review", "is_open"),
Output("modal_background", "style"),
Output("modal", "is_open"),
Output("modal_body", "children"),
Input("review", "n_clicks"),
Input("modal_background", "n_clicks"),
Input("FAQ_button", "n_clicks"),
Input("offcanvas_close", "n_clicks"),
Input("modal_close", "n_clicks"),
Input("contact_us", "n_clicks"),
prevent_initial_call = True
)
def review_right_sidebar(oc_click, bg_click, FAQ_click, oc_close, FAQ_close, cu_clicks):
if not oc_click and not bg_click and not FAQ_click and not oc_close and not FAQ_close and not cu_clicks:
raise PreventUpdate
print("CALLBACK: review", oc_click, dash.ctx.triggered_id)
trigger = dash.ctx.triggered_id
if trigger == "modal_background" or trigger == "offcanvas_close" or trigger == "modal_close": # Background, close all
return False, {"display":"none"}, False, None
if trigger == "review" and oc_click:
return True, {"display":"flex"}, False, None
elif trigger == "FAQ_button" and FAQ_click: #modal / FAQs
return False, {"display":"flex"}, True, struct.FAQ()
elif trigger == "contact_us" and cu_clicks:
return False, {"display":"flex"}, True, struct.contact_us()
else:
# strange case - after sidebar click, gets past first prevent update. This is second check to make sure not triggered by spawning in.
raise PreventUpdate
@app.callback(
Output({'type': 'source_collapse', 'index': MATCH}, 'is_open'),
Input({'type': 'source_collapse_button', 'index': MATCH}, 'n_clicks'),
State({'type': 'source_collapse', 'index': MATCH}, 'is_open'),
prevent_initial_call = True
)
def sidebar_collapse(_, state):
trigger = dash.ctx.triggered_id
print("CALLBACK: toggling collapse. Trigger = {}".format(trigger))
return not state
@app.callback(
Output('active_source','data'),
Input({"type": "source_title", "index": ALL}, 'n_clicks'),
Input({"type": "main_search_source_links", "index": ALL}, 'n_clicks'),
Input({"type": "source_links", "index": ALL}, 'n_clicks'),
Input('url', 'href'),
prevent_initial_call = True
)
def sidebar_schema(open_study_schema, links1, links2, href):
'''
When the active item in the accordion is changed
Read the active schema NOTE with new system, could make active_source redundant
Read the previous schema
Read the open schemas.
'''
trigger = dash.ctx.triggered_id
print("CALLBACK: schema change, trigger: {}".format(trigger))# #Trigger: {}, open_schema = {}, links1 {}, links2 {}".format(trigger, open_study_schema, links1, links2))
if trigger=="url":
# Parse the URL and extract query parameters
parsed_url = urlparse(href)
params = parse_qs(parsed_url.query)
input_value = params.get('source', [''])[0]
if len(input_value) == 0:
print("preventing schema update")
raise PreventUpdate
return str(input_value)
else:
real_triggers = [x for x in open_study_schema if (x and x>0)] + [x for x in links1 if (x and x>0)] +[x for x in links2 if (x and x>0)]
if len(real_triggers) == 0 :
raise PreventUpdate
open_study_schema = trigger["index"]
return open_study_schema
@app.callback(
Output('active_dataset','data'),
Output({"type": "table_tabs", "index": ALL}, 'value'),
Input({"type": "table_tabs", "index": ALL}, 'value'),
Input({"type": "search_metadata_table", "index": ALL}, "active_cell"),
State({"type": "search_metadata_table", "index": ALL}, "data"),
prevent_initial_call = True
)
def sidebar_table(tables, active_cell, data):
'''
When the active table_tab changes
When the schema changes
Read the current active table
Update the active table
Update the activated table tabs (deactivate previously activated tabs)
'''
#print(active_cell)
#print(data)
if active_cell and len(active_cell) > 1:
active_cell = active_cell[1]
#active_cell_i = active_cell[1]["row"]
data = data[0]
if tables == None:
raise PreventUpdate
print("\nCALLBACK: sidebar table click, trigger: {},".format(dash.ctx.triggered_id))
if active_cell and len(active_cell) > 1:
cell_click = data[active_cell["row"]]["Source"] + "-" + data[active_cell["row"]]["Dataset"]
print("debug cell click", cell_click)
return cell_click, ["None" for t in tables]
active = [t for t in tables if (t!= None and t!='None')]
# if no tables are active
if len(active) == 0:
raise PreventUpdate
# if more than one table is active
elif len(active) != 1:
print("Error 12: More than one activated tab:", active)
table = active[0]
return table, ["None" for t in tables]
@app.callback(
Output("sidebar_list_div", "children"),
Output("search_metadata_div", "children"),
Output("search_text", "children"),
Output("sidebar_filter", "children"),
Output("toggle_values", "style"),
Input("search_button", "n_clicks"),
Input("main_search", "n_submit"),
State("main_search", "value"),
Input("include_dropdown", "value"),
Input("exclude_dropdown", "value"),
Input("tags_search", "value"),
Input("collection_age_slider", "value"),
Input("collection_time_slider", "value"),
Input("search_type_radio", "value"),
Input("include_type_checkbox", "value"),
Input("toggle_values", "value"),
State({'type': 'source_collapse', 'index': ALL}, 'id'),
State({'type': 'source_collapse', 'index': ALL}, 'is_open'),
State("shopping_basket", "data"),
State("active_dataset", "data"),
)
def main_search(click, enter, s, include_dropdown, exclude_dropdown, cl_1, age_slider, time_slider, search_type,include_type, toggle_values, screen_schemas, open_schemas, shopping_basket, table):
'''
When the search button is clicked
read the main search content
read the include dropdown value
read the exclude dropdown value
read the search_checklist_1 value
read the collection_age_slider value
read the collection_time_slider value
(etc, may be more added later
Read the current active schema
Read the current shopping basket
Read the active table
Update the sidebar div
Version 1: search by similar text in schema, table name or keywords.
these may be branched into different search functions later, but for now will do the trick
Do we want it on button click or auto filter?
Probs on button click, that way we minimise what could be quite complex filtering
'''
trigger = dash.ctx.triggered_id
print("CALLBACK: main search, searching value: {}, trigger {}.".format(s, trigger))
print("include_type_checklist", include_type)
#print(" DEBUG search: click {}, {}, {}, {}, {}, {}, {}".format(click, s, include_dropdown, exclude_dropdown, cl_1, age_slider, time_slider))
# new version 03/1/24 (after a month off so you know its going to be good)
'''
Split by table filtering and variable filtering
table filtering:
1. Get list of distinct tables
2.
'''
# Setting up open schemas
collapse_state = {}
for sch, open in zip(screen_schemas, open_schemas):
if open:
collapse_state[sch["index"]] = True
else:
collapse_state[sch["index"]] = False
#############
time0 = time.time()
# 2. include dropdown & type checkboxes
renamed_include_type = []
if "Study data" in include_type:
renamed_include_type.append("LPS")
if "Linked data" in include_type:
renamed_include_type.append("Linked")
if not include_dropdown:
include_dropdown = spine["source"].drop_duplicates().values
if not exclude_dropdown:
exclude_dropdown = []
must_not = []
else:
must_not = [{
"bool" : {
"should" : [{"term" : { "source" : source}} for source in exclude_dropdown],
}
}
]
if len(s) > 0 :
search = [
{ "regexp": {"table":
{"value" : ".*"+s+".*",
"flags" : "ALL",
"case_insensitive": "true",
"max_determinized_states": 10000,
}
}
},
{ "match": {"table_name": s}},
{ "match": {"long_desc": s}},
{ "match": {"topic_tags": s}},
{ "match": {"Aims": s}},
{ "match": {"Themes": s}},
]
else:
search = []
if cl_1 : # Tags:
tags = [{"term" : { "topic_tags" : tag}} for tag in cl_1] + [{"term" : { "Themes" : tag}} for tag in cl_1]
else:
tags = []
collection_times = ["01/1940", "01/1950", "01/1960", "01/1970", "01/1980", "01/1990", "01/2000", "01/2010", "01/2020", "01/2030"]
# SPINE SEARCH
all_query = {
"query": {
"bool" : {
"filter":[{
"bool" : {
"should" : [{"term" : { "source" : source}} for source in include_dropdown]
}
},
{
"bool" : {
"should" : tags
}
},
],
"must_not": must_not,
"must" : [{
"bool" : {
"should" : search
}
},
{
"bool" : {
"should" : [
{"range": {
"lf" : {
"gte" : age_slider[0], # lower range
"lte" : age_slider[1] # upper range
},
}},
{"range": {
"q2" : {
"gte" : age_slider[0], # lower range
"lte" : age_slider[1] # upper range
},
}},
{"range": {
"uf" : {
"gte" : age_slider[0], # lower range
"lte" : age_slider[1] # upper range
},
}},
],
}
},
{
"bool" : {
"should" : [
{"range": {
"collection_start" : {
"gte" : collection_times[time_slider[0]],
"lte" : collection_times[time_slider[1]],
"format" : "MM/YYYY"
}
}},
{"range": {
"collection_end" : {
"gte" : collection_times[time_slider[0]],
"lte" : collection_times[time_slider[1]],
"format" : "MM/YYYY"
}
}},
],
}
}
],
}
}
}
r1 = es.search(index="index_spine", body=all_query, size = 1000)
sidebar_results = []
for hit in r1["hits"]["hits"]:
#print(hit)
sidebar_results.append({key: hit["_source"][key] for key in ["source", "source_name", "table", "table_name", "Type"]})
if len(sidebar_results) == len(spine):
sidebar_text= "Showing full catalogue"
else:
sidebar_text = "Hiding {} datasets from search filters".format(len(spine) - len(sidebar_results))
toggle_values_style = {"display" : "none"}
# only if searching by source
if search_type.lower() == "sources":
search_results = []
for hit in r1["hits"]["hits"]:
search_results.append({key: hit["_source"][key] for key in ["source", "source_name", "Aims", "Type"]})
if len(search_results) != 0:
info = pd.DataFrame(search_results).drop_duplicates(subset=["source"])
search_results_table = struct.sources_list(app, info, "main_search")
search_text = "Showing {} data sources".format(len(set(info["source"])))
else:
search_results_table = None
search_text = "No results"
elif search_type.lower() == "datasets":
# reuse sidebar results
search_results = []
for hit in r1["hits"]["hits"]:
search_results.append({key: hit["_source"][key] for key in ["source", "table"]})
if len(search_results) != 0:
info = pd.DataFrame(search_results)
info = pd.merge(info, datasets_df, how="left", on = ["source", "table"])
info = info[["source", "table", "short_desc"]].rename(columns={"source":"Source", "table": "Dataset", "short_desc": "Description"})
search_results_table = struct.make_table(info, "search_metadata_table", "datasets_search")
search_text = "Showing {} datasets".format(len(info))
else:
search_results_table = None
search_text = "No results"
elif search_type.lower() == "variables": # variables
'''
TODO 02/07/2024
This is too slow. I think its the volume of values & desks.
1. Test if this is the case. Measure search time & build time separately
2. Provided search time isn't the major issue, move to memory all_metadata and try to efficiently join return ids on that.
3. Store current returned response table in memory and immediately provided if the search terms have not changed
Likely requires storing the search terms as well as the table
----
ok, suddenly its performing well. Suspicious... I'll keep my eye on you
but point remains, build time is approx .1-.2 seconds. Not great, but not terrible. We can live with that. Main thing is search.
'''
if len(s) > 0 :
search = [{ "term": {"topic_tags": s}},
{ "term": {"Themes": s}},
{"match" : {"variable_name" : s}},
{ "regexp": {"variable_name":
{"value" : ".*"+s+".*",
"flags" : "ALL",
"case_insensitive": "true",
"max_determinized_states": 10000,
}
}
},
{"match" : {"variable_description" : s}},