forked from ocean-data-factory-sweden/kso-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patht2_utils.py
More file actions
2108 lines (1739 loc) · 73.6 KB
/
Copy patht2_utils.py
File metadata and controls
2108 lines (1739 loc) · 73.6 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
# base imports
import os
import pandas as pd
import subprocess
import datetime
import logging
# widget imports
import ipywidgets as widgets
from ipywidgets import interactive, Layout, HBox
from IPython.display import display
import asyncio
# util imports
import kso_utils.movie_utils as movie_utils
import kso_utils.server_utils as server_utils
import kso_utils.tutorials_utils as t_utils
# Logging
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
out_df = pd.DataFrame()
####################################################
############### SURVEY FUNCTIONS ###################
####################################################
def select_survey(db_info_dict: dict):
"""
This function allows the user to select an existing survey from a dropdown menu or create a new
survey by filling out a series of widgets
:param db_info_dict: a dictionary with the following keys:
:type db_info_dict: dict
:return: A widget with a dropdown menu with two options: 'Existing' and 'New survey'.
"""
# Load the csv with surveys information
surveys_df = pd.read_csv(db_info_dict["local_surveys_csv"])
# Existing Surveys
exisiting_surveys = surveys_df.SurveyName.unique()
def f(Existing_or_new):
if Existing_or_new == "Existing":
survey_widget = widgets.Dropdown(
options=exisiting_surveys,
description="Survey Name:",
disabled=False,
layout=Layout(width="80%"),
style={"description_width": "initial"},
)
display(survey_widget)
return survey_widget
if Existing_or_new == "New survey":
# Load the csv with with sites and survey choices
choices_df = pd.read_csv(db_info_dict["local_choices_csv"])
# Save the new survey responses into a dict
survey_info = {
# Write the name of the encoder
"EncoderName": record_encoder(),
# Select the start date of the survey
"SurveyStartDate": select_SurveyStartDate(),
# Write the name of the survey
"SurveyName": write_SurveyName(),
# Select the DOC office
"OfficeName": select_OfficeName(
choices_df.OfficeName.dropna().unique().tolist()
),
# Write the name of the contractor
"ContractorName": write_ContractorName(),
# Write the number of the contractor
"ContractNumber": write_ContractNumber(),
# Write the link to the contract
"LinkToContract": write_LinkToContract(),
# Record the name of the survey leader
"SurveyLeaderName": write_SurveyLeaderName(),
# Select the name of the linked Marine Reserve
"LinkToMarineReserve": select_LinkToMarineReserve(
choices_df.MarineReserve.dropna().unique().tolist()
),
# Specify if survey is single species
"FishMultiSpecies": select_FishMultiSpecies(),
# Specify how the survey was stratified
"StratifiedBy": select_StratifiedBy(
choices_df.StratifiedBy.dropna().unique().tolist()
),
# Select if survey is part of long term monitoring
"IsLongTermMonitoring": select_IsLongTermMonitoring(),
# Specify the site selection of the survey
"SiteSelectionDesign": select_SiteSelectionDesign(
choices_df.SiteSelection.dropna().unique().tolist()
),
# Specify the unit selection of the survey
"UnitSelectionDesign": select_UnitSelectionDesign(
choices_df.UnitSelection.dropna().unique().tolist()
),
# Select the type of right holder of the survey
"RightsHolder": select_RightsHolder(
choices_df.RightsHolder.dropna().unique().tolist()
),
# Write who can access the videos/resources
"AccessRights": select_AccessRights(),
# Write a description of the survey design and objectives
"SurveyVerbatim": write_SurveyVerbatim(),
# Select the type of BUV
"BUVType": select_BUVType(
choices_df.BUVType.dropna().unique().tolist()
),
# Write the link to the pictures
"LinkToPicture": write_LinkToPicture(),
# Write the name of the vessel
"Vessel": write_Vessel(),
# Write the link to the fieldsheets
"LinkToFieldSheets": write_LinkToFieldSheets(),
# Write the link to LinkReport01
"LinkReport01": write_LinkReport01(),
# Write the link to LinkReport02
"LinkReport02": write_LinkReport02(),
# Write the link to LinkReport03
"LinkReport03": write_LinkReport03(),
# Write the link to LinkReport04
"LinkReport04": write_LinkReport04(),
# Write the link to LinkToOriginalData
"LinkToOriginalData": write_LinkToOriginalData(),
}
return survey_info
w = interactive(
f,
Existing_or_new=widgets.Dropdown(
options=["Existing", "New survey"],
description="Existing or new survey:",
disabled=False,
layout=Layout(width="90%"),
style={"description_width": "initial"},
),
)
display(w)
return w
def record_encoder():
"""
> This function creates a widget that asks for the name of the person encoding the survey
information
:return: The name of the person encoding the survey information
"""
# Widget to record the encoder of the survey information
EncoderName_widget = widgets.Text(
placeholder="First and last name",
description="Name of the person encoding this survey information:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(EncoderName_widget)
return EncoderName_widget
def select_SurveyStartDate():
"""
> This function creates a widget that allows the user to select a date
:return: A widget that allows the user to select a date.
"""
# Widget to record the start date of the survey
SurveyStartDate_widget = widgets.DatePicker(
description="Offical date when survey started as a research event",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(SurveyStartDate_widget)
return SurveyStartDate_widget
def write_SurveyName():
"""
> This function creates a widget that allows the user to enter a name for the survey
:return: A widget object
"""
# Widget to record the name of the survey
SurveyName_widget = widgets.Text(
placeholder="Baited Underwater Video Taputeranga Apr 2015",
description="A name for this survey:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(SurveyName_widget)
return SurveyName_widget
def select_OfficeName(OfficeName_options: list):
"""
> This function creates a dropdown widget that allows the user to select the name of the DOC Office
responsible for the survey
:param OfficeName_options: a list of the names of the DOC offices that are responsible for the
survey
:return: The widget is being returned.
"""
# Widget to record the name of the linked DOC Office
OfficeName_widget = widgets.Dropdown(
options=OfficeName_options,
description="Department of Conservation Office responsible for this survey:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(OfficeName_widget)
return OfficeName_widget
def write_ContractorName():
"""
> This function creates a widget that allows the user to enter the name of the contractor
:return: The widget is being returned.
"""
# Widget to record the name of the contractor
ContractorName_widget = widgets.Text(
placeholder="No contractor",
description="Person/company contracted to carry out the survey:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(ContractorName_widget)
return ContractorName_widget
def write_ContractNumber():
"""
> This function creates a widget that allows the user to enter the contract number for the survey
:return: The widget is being returned.
"""
# Widget to record the number of the contractor
ContractNumber_widget = widgets.Text(
description="Contract number for this survey:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(ContractNumber_widget)
return ContractNumber_widget
def write_LinkToContract():
"""
> This function creates a widget that allows the user to enter a hyperlink to the contract related
to the survey
:return: The widget
"""
# Widget to record the link to the contract
LinkToContract_widget = widgets.Text(
description="Hyperlink to the DOCCM for the contract related to this survey:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(LinkToContract_widget)
return LinkToContract_widget
def write_SurveyLeaderName():
"""
> This function creates a widget that allows the user to enter the name of the person in charge of
the survey
:return: The widget is being returned.
"""
# Widget to record the name of the survey leader
SurveyLeaderName_widget = widgets.Text(
placeholder="First and last name",
description="Name of the person in charge of this survey:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(SurveyLeaderName_widget)
return SurveyLeaderName_widget
def select_LinkToMarineReserve(reserves_available: list):
"""
> This function creates a dropdown widget that allows the user to select the name of the Marine
Reserve that the survey is linked to
:param reserves_available: a list of the names of the Marine Reserves that are available to be
linked to the survey
:return: The name of the Marine Reserve linked to the survey
"""
# Widget to record the name of the linked Marine Reserve
LinkToMarineReserve_widget = widgets.Dropdown(
options=reserves_available,
description="Marine Reserve linked to the survey:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(LinkToMarineReserve_widget)
return LinkToMarineReserve_widget
def select_FishMultiSpecies():
"""
> This function creates a widget that allows the user to select whether the survey is a single
species survey or not
:return: A widget that can be used to select a single species or multiple species
"""
# Widget to record if survey is single species
def FishMultiSpecies_to_true_false(FishMultiSpecies_value):
if FishMultiSpecies_value == "Yes":
return False
else:
return True
w = interactive(
FishMultiSpecies_to_true_false,
FishMultiSpecies_value=widgets.Dropdown(
options=["No", "Yes"],
description="Does this survey look at a single species?",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
),
)
display(w)
return w
def select_StratifiedBy(StratifiedBy_choices: list):
"""
> This function creates a dropdown widget that allows the user to select the stratified factors for
the sampling design
:param StratifiedBy_choices: a list of choices for the dropdown menu
:return: A widget object
"""
# Widget to record if survey was stratified by any factor
StratifiedBy_widget = widgets.Dropdown(
options=StratifiedBy_choices,
description="Stratified factors for the sampling design",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(StratifiedBy_widget)
return StratifiedBy_widget
def select_IsLongTermMonitoring():
"""
> This function creates a widget that allows the user to select whether the survey is part of a
long-term monitoring
:return: A widget object
"""
# Widget to record if survey is part of long term monitoring
def IsLongTermMonitoring_to_true_false(IsLongTermMonitoring_value):
if IsLongTermMonitoring_value == "No":
return False
else:
return True
w = interactive(
IsLongTermMonitoring_to_true_false,
IsLongTermMonitoring_value=widgets.Dropdown(
options=["Yes", "No"],
description="Is the survey part of a long-term monitoring?",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
),
)
display(w)
return w
def select_SiteSelectionDesign(site_selection_options: list):
"""
This function creates a dropdown widget that allows the user to select the site selection design of
the survey
:param site_selection_options: a list of strings that are the options for the dropdown menu
:return: A widget
"""
# Widget to record the site selection of the survey
SiteSelectionDesign_widget = widgets.Dropdown(
options=site_selection_options,
description="What was the design for site selection?",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(SiteSelectionDesign_widget)
return SiteSelectionDesign_widget
def select_UnitSelectionDesign(unit_selection_options: list):
"""
> This function creates a dropdown widget that allows the user to select the design for site
selection
:param unit_selection_options: list
:type unit_selection_options: list
:return: A widget that allows the user to select the unit selection design of the survey.
"""
# Widget to record the unit selection of the survey
UnitSelectionDesign_widget = widgets.Dropdown(
options=unit_selection_options,
description="What was the design for unit selection?",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(UnitSelectionDesign_widget)
return UnitSelectionDesign_widget
def select_RightsHolder(RightsHolder_options: list):
"""
> This function creates a dropdown widget that allows the user to select the type of right holder of
the survey
:param RightsHolder_options: a list of options for the dropdown menu
:return: A widget
"""
# Widget to record the type of right holder of the survey
RightsHolder_widget = widgets.Dropdown(
options=RightsHolder_options,
description="Person(s) or organization(s) owning or managing rights over the resource",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(RightsHolder_widget)
return RightsHolder_widget
def select_AccessRights():
"""
> This function creates a widget that asks the user to enter information about who can access the
resource
:return: A widget object
"""
# Widget to record information about who can access the resource
AccessRights_widget = widgets.Text(
placeholder="",
description="Who can access the resource?",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(AccessRights_widget)
return AccessRights_widget
def write_SurveyVerbatim():
"""
> This function creates a widget that allows the user to enter a description of the survey design
and objectives
:return: A widget
"""
# Widget to record description of the survey design and objectives
SurveyVerbatim_widget = widgets.Textarea(
placeholder="",
description="Provide an exhaustive description of the survey design and objectives",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(SurveyVerbatim_widget)
return SurveyVerbatim_widget
def select_BUVType(BUVType_choices: list):
"""
> This function creates a dropdown widget that allows the user to select the type of BUV used for
the survey
:param BUVType_choices: list
:type BUVType_choices: list
:return: A widget
"""
# Widget to record the type of BUV
BUVType_widget = widgets.Dropdown(
options=BUVType_choices,
description="Type of BUV used for the survey:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(BUVType_widget)
return BUVType_widget
def write_LinkToPicture():
"""
> This function creates a text box for the user to enter the link to the DOCCM folder for the survey
photos
:return: The widget is being returned.
"""
# Widget to record the link to the pictures
LinkToPicture_widget = widgets.Text(
description="Hyperlink to the DOCCM folder for this survey photos:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(LinkToPicture_widget)
return LinkToPicture_widget
def write_Vessel():
"""
This function creates a widget that allows the user to enter the name of the vessel that deployed
the unit
:return: The name of the vessel used to deploy the unit.
"""
# Widget to record the name of the vessel
Vessel_widget = widgets.Text(
description="Vessel used to deploy the unit:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(Vessel_widget)
return Vessel_widget
def write_LinkToFieldSheets():
"""
**write_LinkToFieldSheets()**: This function creates a text box for the user to enter a hyperlink to
the DOCCM for the field sheets used to gather the survey information
:return: The text box widget.
"""
LinkToFieldSheets = widgets.Text(
description="Hyperlink to the DOCCM for the field sheets used to gather the survey information:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(LinkToFieldSheets)
return LinkToFieldSheets
def write_LinkReport01():
"""
> This function creates a text box for the user to enter a hyperlink to the first (of up to four)
DOCCM report related to these data
:return: The text box.
"""
LinkReport01 = widgets.Text(
description="Hyperlink to the first (of up to four) DOCCM report related to these data:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(LinkReport01)
return LinkReport01
def write_LinkReport02():
"""
**write_LinkReport02()**: This function creates a text box for the user to enter a hyperlink to the
second DOCCM report related to these data
:return: The text box widget.
"""
LinkReport02 = widgets.Text(
description="Hyperlink to the second DOCCM report related to these data:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(LinkReport02)
return LinkReport02
def write_LinkReport03():
"""
**write_LinkReport03()**: This function creates a text box for the user to enter a hyperlink to the
third DOCCM report related to these data
:return: The text box widget.
"""
LinkReport03 = widgets.Text(
description="Hyperlink to the third DOCCM report related to these data:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(LinkReport03)
return LinkReport03
def write_LinkReport04():
"""
**write_LinkReport04()**: This function creates a text box for the user to enter a hyperlink to the
fourth DOCCM report related to these data
:return: The text box widget.
"""
LinkReport04 = widgets.Text(
description="Hyperlink to the fourth DOCCM report related to these data:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(LinkReport04)
return LinkReport04
def write_LinkToOriginalData():
"""
> This function creates a text box that allows the user to enter a hyperlink to the DOCCM for the
spreadsheet where these data were intially encoded
:return: A text box with a description.
"""
LinkToOriginalData = widgets.Text(
description="Hyperlink to the DOCCM for the spreadsheet where these data were intially encoded:",
disabled=False,
layout=Layout(width="95%"),
style={"description_width": "initial"},
)
display(LinkToOriginalData)
return LinkToOriginalData
# Confirm the details of the survey
def confirm_survey(survey_i, db_info_dict: dict):
"""
It takes the survey information and checks if it's a new survey or an existing one. If it's a new
survey, it saves the information in the survey csv file. If it's an existing survey, it prints the
information for the pre-existing survey
:param survey_i: the survey widget
:param db_info_dict: a dictionary with the following keys:
"""
correct_button = widgets.Button(
description="Yes, details are correct",
layout=Layout(width="25%"),
style={"description_width": "initial"},
button_style="danger",
)
wrong_button = widgets.Button(
description="No, I will go back and fix them",
layout=Layout(width="45%"),
style={"description_width": "initial"},
button_style="danger",
)
# If new survey, review details and save changes in survey csv server
if isinstance(survey_i.result, dict):
# Save the responses as a new row for the survey csv file
new_survey_row_dict = {
key: (
value.value
if hasattr(value, "value")
else value.result
if isinstance(value.result, int)
else value.result.value
)
for key, value in survey_i.result.items()
}
new_survey_row = pd.DataFrame.from_records(new_survey_row_dict, index=[0])
# Load the csv with sites and survey choices
choices_df = pd.read_csv(db_info_dict["local_choices_csv"])
# Get prepopulated fields for the survey
new_survey_row["OfficeContact"] = choices_df[
choices_df["OfficeName"] == new_survey_row.OfficeName.values[0]
]["OfficeContact"].values[0]
new_survey_row[["SurveyLocation", "Region"]] = choices_df[
choices_df["MarineReserve"] == new_survey_row.LinkToMarineReserve.values[0]
][["MarineReserveAbreviation", "Region"]].values[0]
new_survey_row["DateEntry"] = datetime.date.today()
new_survey_row["SurveyType"] = "BUV"
new_survey_row["SurveyID"] = (
new_survey_row["SurveyLocation"]
+ "_"
+ new_survey_row["SurveyStartDate"].values[0].strftime("%Y%m%d")
+ "_"
+ new_survey_row["SurveyType"]
)
# Review details
print("The details of the new survey are:")
for ind in new_survey_row.T.index:
print(ind, "-->", new_survey_row.T[0][ind])
# Save changes in survey csv locally and in the server
async def f(new_survey_row):
x = await t_utils.wait_for_change(
correct_button, wrong_button
) # <---- Pass both buttons into the function
if (
x == "Yes, details are correct"
): # <--- use if statement to trigger different events for the two buttons
# Load the csv with sites information
surveys_df = pd.read_csv(db_info_dict["local_surveys_csv"])
# Drop unnecessary columns
# new_survey_row = new_survey_row.drop(columns=['ShortFolder'])
# Check the columns are the same
diff_columns = list(
set(surveys_df.columns.sort_values().values)
- set(new_survey_row.columns.sort_values().values)
)
if len(diff_columns) > 0:
logging.error(
f"The {diff_columns} columns are missing from the survey information."
)
raise
# Check if the survey exist in the csv
if new_survey_row.SurveyID.unique()[0] in surveys_df.SurveyID.unique():
logging.error(
f"The survey {new_survey_row.SurveyID.unique()[0]} already exists in the database."
)
raise
print("Updating the new survey information.")
# Add the new row to the choices df
surveys_df = surveys_df.append(new_survey_row, ignore_index=True)
# Save the updated df locally
surveys_df.to_csv(db_info_dict["local_surveys_csv"], index=False)
# Save the updated df in the server
server_utils.upload_file_to_s3(
db_info_dict["client"],
bucket=db_info_dict["bucket"],
key=db_info_dict["server_surveys_csv"],
filename=db_info_dict["local_surveys_csv"].__str__(),
)
print("Survey information updated!")
else:
print("Come back when the data is tidy!")
# If existing survey print the info for the pre-existing survey
else:
# Load the csv with surveys information
surveys_df = pd.read_csv(db_info_dict["local_surveys_csv"])
# Select the specific survey info
new_survey_row = surveys_df[
surveys_df["SurveyName"] == survey_i.result.value
].reset_index(drop=True)
print("The details of the selected survey are:")
for ind in new_survey_row.T.index:
print(ind, "-->", new_survey_row.T[0][ind])
async def f(new_survey_row):
x = await t_utils.wait_for_change(
correct_button, wrong_button
) # <---- Pass both buttons into the function
if (
x == "Yes, details are correct"
): # <--- use if statement to trigger different events for the two buttons
print("Great, you can start uploading the movies.")
else:
print("Come back when the data is tidy!")
print("")
print("")
print("Are the survey details above correct?")
display(
HBox([correct_button, wrong_button])
) # <----Display both buttons in an HBox
asyncio.create_task(f(new_survey_row))
####################################################
############### MOVIES FUNCTIONS ###################
####################################################
def get_survey_name(survey_i):
"""
If the survey is new, save the responses for the new survey as a dataframe. If the survey is
existing, return the name of the survey
:param survey_i: the survey object
:return: The name of the survey
"""
# If new survey, review details and save changes in survey csv server
if isinstance(survey_i.result, dict):
# Save the responses for the new survey as a dataframe
new_survey_row_dict = {
key: (
value.value
if hasattr(value, "value")
else value.result
if isinstance(value.result, int)
else value.result.value
)
for key, value in survey_i.result.items()
}
survey_name = new_survey_row_dict["SurveyName"]
# If existing survey print the info for the pre-existing survey
else:
# Return the name of the survey
survey_name = survey_i.result.value
return survey_name
def select_deployment(project, db_info_dict: dict, survey_i):
"""
This function allows the user to select a deployment from a survey of interest
:param project: the name of the project
:param db_info_dict: a dictionary with the following keys:
:type db_info_dict: dict
:param survey_i: the index of the survey you want to download
"""
# Load the csv with with sites and survey choices
choices_df = pd.read_csv(db_info_dict["local_choices_csv"])
# Read surveys csv
surveys_df = pd.read_csv(
db_info_dict["local_surveys_csv"], parse_dates=["SurveyStartDate"]
)
# Get the name of the survey
survey_name = get_survey_name(survey_i)
# Save the SurveyID that match the survey name
survey_row = surveys_df[surveys_df["SurveyName"] == survey_name].reset_index(
drop=True
)
# Save the year of the survey
# survey_year = survey_row["SurveyStartDate"].values[0].strftime("%Y")
survey_year = survey_row["SurveyStartDate"].dt.year.values[0]
# Get prepopulated fields for the survey
survey_row[["ShortFolder"]] = choices_df[
choices_df["MarineReserve"] == survey_row.LinkToMarineReserve.values[0]
][["ShortFolder"]].values[0]
# Save the "server filename" of the survey
short_marine_reserve = survey_row["ShortFolder"].values[0]
# Save the "server filename" of the survey
survey_server_name = short_marine_reserve + "-buv-" + str(survey_year) + "/"
# Retrieve deployments info from the survey of interest
deployments_server_name = db_info_dict["client"].list_objects(
Bucket=db_info_dict["bucket"], Prefix=survey_server_name, Delimiter="/"
)
# Convert info to dataframe
deployments_server_name = pd.DataFrame.from_dict(
deployments_server_name["CommonPrefixes"]
)
# Select only the name of the "deployment folder"
deployments_server_name_list = deployments_server_name.Prefix.str.split("/").str[1]
# Widget to select the deployment of interest
deployment_widget = widgets.SelectMultiple(
options=deployments_server_name_list,
description="New deployment:",
disabled=False,
layout=Layout(width="50%"),
style={"description_width": "initial"},
)
display(deployment_widget)
return deployment_widget, survey_row, survey_server_name
def select_eventdate(survey_row: pd.DataFrame):
"""
> This function creates a date picker widget that allows the user to select the date of the survey.
The default date is the beginning of the survey
:param survey_row: a dataframe containing survey information
:return: A widget object
"""
# Set the beginning of the survey as default date
default_date = pd.Timestamp(survey_row["SurveyStartDate"].values[0]).to_pydatetime()
# Select the date
date_widget = widgets.DatePicker(
description="Date of deployment:",
value=default_date,
disabled=False,
layout=Layout(width="50%"),
style={"description_width": "initial"},
)
display(date_widget)
return date_widget
def check_deployment(
deployment_selected: widgets.Widget,
deployment_date: widgets.Widget,
survey_server_name: str,
db_info_dict: dict,
survey_i,
):
"""
This function checks if the deployment selected by the user is already in the database. If it is, it
will raise an error. If it is not, it will return the deployment filenames
:param deployment_selected: a list of the deployment names selected by the user
:param deployment_date: the date of the deployment
:param survey_server_name: The name of the survey in the server
:param db_info_dict: a dictionary containing the following keys:
:param survey_i: the index of the survey you want to upload to
:return: A list of deployment filenames
"""
# Ensure at least one deployment has been selected
if not deployment_selected.value:
logging.error("Please select a deployment.")
raise
# Get list of movies available in server from that survey
deployments_in_server_df = server_utils.get_matching_s3_keys(
db_info_dict["client"], db_info_dict["bucket"], prefix=survey_server_name
)
# Get a list of the movies in the server
files_in_server = deployments_in_server_df.Key.str.split("/").str[-1].to_list()
deployments_in_server = [
file
for file in files_in_server
if file[-3:] in movie_utils.get_movie_extensions()
]
# Read surveys csv
surveys_df = pd.read_csv(
db_info_dict["local_surveys_csv"], parse_dates=["SurveyStartDate"]
)
# Get the name of the survey
survey_name = get_survey_name(survey_i)
# Save the SurveyID that match the survey name
SurveyID = surveys_df[surveys_df["SurveyName"] == survey_name].SurveyID.to_list()[0]
# Read movie.csv info
movies_df = pd.read_csv(db_info_dict["local_movies_csv"])
# Get a list of deployment names from the csv of the survey of interest
deployment_in_csv = movies_df[movies_df["SurveyID"] == SurveyID].filename.to_list()
# Save eventdate as str
EventDate_str = deployment_date.value.strftime("%d_%m_%Y")
deployment_filenames = []
for deployment_i in deployment_selected.value:
# Specify the name of the deployment
deployment_name = deployment_i + "_" + EventDate_str
if deployment_name in deployment_in_csv:
logging.error(
f"Deployment {deployment_name} already exist in the csv file reselect new deployments before going any further!"
)
raise
# Specify the filename of the deployment
filename = deployment_name + ".MP4"
if filename in deployments_in_server:
logging.error(
f"Deployment {deployment_name} already exist in the server reselect new deployments before going any further!"
)
raise
else:
deployment_filenames = deployment_filenames + [filename]
print(
"There is no existing information in the database for",
deployment_filenames,
"You can continue uploading the information.",
)
return deployment_filenames
def update_new_deployments(
deployment_filenames: list,