File size: 60,216 Bytes
9ad0e2d
 
 
 
 
 
 
 
 
 
 
 
 
f366666
9ad0e2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
import ee
import os
import datetime
import fiona
import geopandas as gpd
import folium
import streamlit as st
import geemap.colormaps as cm
import geemap.foliumap as geemap
from datetime import date
from .rois import *


@st.cache(allow_output_mutation=True)
def uploaded_file_to_gdf(data):
    import tempfile
    import os
    import uuid

    _, file_extension = os.path.splitext(data.name)
    file_id = str(uuid.uuid4())
    file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{file_extension}")

    with open(file_path, "wb") as file:
        file.write(data.getbuffer())

    if file_path.lower().endswith(".kml"):
        fiona.drvsupport.supported_drivers["KML"] = "rw"
        gdf = gpd.read_file(file_path, driver="KML")
    else:
        gdf = gpd.read_file(file_path)

    return gdf


def app():

    today = date.today()

    st.title("Create Timelapse")

    st.markdown(
        """
        An interactive web app for creating [Landsat](https://developers.google.com/earth-engine/datasets/catalog/landsat)/[GOES](https://jstnbraaten.medium.com/goes-in-earth-engine-53fbc8783c16) timelapse for any location around the globe. 
        The app was built using [streamlit](https://streamlit.io), [geemap](https://geemap.org), and [Google Earth Engine](https://earthengine.google.com). For more info, check out my streamlit [blog post](https://blog.streamlit.io/creating-satellite-timelapse-with-streamlit-and-earth-engine). 
    """
    )

    row1_col1, row1_col2 = st.columns([2, 1])

    if st.session_state.get("zoom_level") is None:
        st.session_state["zoom_level"] = 4

    st.session_state["ee_asset_id"] = None
    st.session_state["bands"] = None
    st.session_state["palette"] = None
    st.session_state["vis_params"] = None

    with row1_col1:
        m = geemap.Map(
            basemap="HYBRID",
            plugin_Draw=True,
            Draw_export=True,
            locate_control=True,
            plugin_LatLngPopup=False,
        )
        m.add_basemap("ROADMAP")

    with row1_col2:

        keyword = st.text_input("Search for a location:", "")
        if keyword:
            locations = geemap.geocode(keyword)
            if locations is not None and len(locations) > 0:
                str_locations = [str(g)[1:-1] for g in locations]
                location = st.selectbox("Select a location:", str_locations)
                loc_index = str_locations.index(location)
                selected_loc = locations[loc_index]
                lat, lng = selected_loc.lat, selected_loc.lng
                folium.Marker(location=[lat, lng], popup=location).add_to(m)
                m.set_center(lng, lat, 12)
                st.session_state["zoom_level"] = 12

        collection = st.selectbox(
            "Select a satellite image collection: ",
            [
                "Any Earth Engine ImageCollection",
                "Landsat TM-ETM-OLI Surface Reflectance",
                "Sentinel-2 MSI Surface Reflectance",
                "Geostationary Operational Environmental Satellites (GOES)",
                "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km",
                "MODIS Gap filled Land Surface Temperature Daily",
                "MODIS Ocean Color SMI",
                "USDA National Agriculture Imagery Program (NAIP)",
            ],
            index=1,
        )

        if collection in [
            "Landsat TM-ETM-OLI Surface Reflectance",
            "Sentinel-2 MSI Surface Reflectance",
        ]:
            roi_options = ["Uploaded GeoJSON"] + list(landsat_rois.keys())

        elif collection == "Geostationary Operational Environmental Satellites (GOES)":
            roi_options = ["Uploaded GeoJSON"] + list(goes_rois.keys())

        elif collection in [
            "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km",
            "MODIS Gap filled Land Surface Temperature Daily",
        ]:
            roi_options = ["Uploaded GeoJSON"] + list(modis_rois.keys())
        elif collection == "MODIS Ocean Color SMI":
            roi_options = ["Uploaded GeoJSON"] + list(ocean_rois.keys())
        else:
            roi_options = ["Uploaded GeoJSON"]

        if collection == "Any Earth Engine ImageCollection":
            keyword = st.text_input("Enter a keyword to search (e.g., MODIS):", "")
            if keyword:

                assets = geemap.search_ee_data(keyword)
                ee_assets = []
                for asset in assets:
                    if asset["ee_id_snippet"].startswith("ee.ImageCollection"):
                        ee_assets.append(asset)

                asset_titles = [x["title"] for x in ee_assets]
                dataset = st.selectbox("Select a dataset:", asset_titles)
                if len(ee_assets) > 0:
                    st.session_state["ee_assets"] = ee_assets
                    st.session_state["asset_titles"] = asset_titles
                    index = asset_titles.index(dataset)
                    ee_id = ee_assets[index]["id"]
                else:
                    ee_id = ""

                if dataset is not None:
                    with st.expander("Show dataset details", False):
                        index = asset_titles.index(dataset)
                        html = geemap.ee_data_html(st.session_state["ee_assets"][index])
                        st.markdown(html, True)
            # elif collection == "MODIS Gap filled Land Surface Temperature Daily":
            #     ee_id = ""
            else:
                ee_id = ""

            asset_id = st.text_input("Enter an ee.ImageCollection asset ID:", ee_id)

            if asset_id:
                with st.expander("Customize band combination and color palette", True):
                    try:
                        col = ee.ImageCollection.load(asset_id)
                        st.session_state["ee_asset_id"] = asset_id
                    except:
                        st.error("Invalid Earth Engine asset ID.")
                        st.session_state["ee_asset_id"] = None
                        return

                    img_bands = col.first().bandNames().getInfo()
                    if len(img_bands) >= 3:
                        default_bands = img_bands[:3][::-1]
                    else:
                        default_bands = img_bands[:]
                    bands = st.multiselect(
                        "Select one or three bands (RGB):", img_bands, default_bands
                    )
                    st.session_state["bands"] = bands

                    if len(bands) == 1:
                        palette_options = st.selectbox(
                            "Color palette",
                            cm.list_colormaps(),
                            index=2,
                        )
                        palette_values = cm.get_palette(palette_options, 15)
                        palette = st.text_area(
                            "Enter a custom palette:",
                            palette_values,
                        )
                        st.write(
                            cm.plot_colormap(cmap=palette_options, return_fig=True)
                        )
                        st.session_state["palette"] = eval(palette)

                    if bands:
                        vis_params = st.text_area(
                            "Enter visualization parameters",
                            "{'bands': ["
                            + ", ".join([f"'{band}'" for band in bands])
                            + "]}",
                        )
                    else:
                        vis_params = st.text_area(
                            "Enter visualization parameters",
                            "{}",
                        )
                    try:
                        st.session_state["vis_params"] = eval(vis_params)
                        st.session_state["vis_params"]["palette"] = st.session_state[
                            "palette"
                        ]
                    except Exception as e:
                        st.session_state["vis_params"] = None
                        st.error(
                            f"Invalid visualization parameters. It must be a dictionary."
                        )

        elif collection == "MODIS Gap filled Land Surface Temperature Daily":
            with st.expander("Show dataset details", False):
                st.markdown(
                    """
                See the [Awesome GEE Community Datasets](https://samapriya.github.io/awesome-gee-community-datasets/projects/daily_lst/).
                """
                )

            MODIS_options = ["Daytime (1:30 pm)", "Nighttime (1:30 am)"]
            MODIS_option = st.selectbox("Select a MODIS dataset:", MODIS_options)
            if MODIS_option == "Daytime (1:30 pm)":
                st.session_state[
                    "ee_asset_id"
                ] = "projects/sat-io/open-datasets/gap-filled-lst/gf_day_1km"
            else:
                st.session_state[
                    "ee_asset_id"
                ] = "projects/sat-io/open-datasets/gap-filled-lst/gf_night_1km"

            palette_options = st.selectbox(
                "Color palette",
                cm.list_colormaps(),
                index=90,
            )
            palette_values = cm.get_palette(palette_options, 15)
            palette = st.text_area(
                "Enter a custom palette:",
                palette_values,
            )
            st.write(cm.plot_colormap(cmap=palette_options, return_fig=True))
            st.session_state["palette"] = eval(palette)
        elif collection == "MODIS Ocean Color SMI":
            with st.expander("Show dataset details", False):
                st.markdown(
                    """
                See the [Earth Engine Data Catalog](https://developers.google.com/earth-engine/datasets/catalog/NASA_OCEANDATA_MODIS-Aqua_L3SMI).
                """
                )

            MODIS_options = ["Aqua", "Terra"]
            MODIS_option = st.selectbox("Select a satellite:", MODIS_options)
            st.session_state["ee_asset_id"] = MODIS_option
            # if MODIS_option == "Daytime (1:30 pm)":
            #     st.session_state[
            #         "ee_asset_id"
            #     ] = "projects/sat-io/open-datasets/gap-filled-lst/gf_day_1km"
            # else:
            #     st.session_state[
            #         "ee_asset_id"
            #     ] = "projects/sat-io/open-datasets/gap-filled-lst/gf_night_1km"

            band_dict = {
                "Chlorophyll a concentration": "chlor_a",
                "Normalized fluorescence line height": "nflh",
                "Particulate organic carbon": "poc",
                "Sea surface temperature": "sst",
                "Remote sensing reflectance at band 412nm": "Rrs_412",
                "Remote sensing reflectance at band 443nm": "Rrs_443",
                "Remote sensing reflectance at band 469nm": "Rrs_469",
                "Remote sensing reflectance at band 488nm": "Rrs_488",
                "Remote sensing reflectance at band 531nm": "Rrs_531",
                "Remote sensing reflectance at band 547nm": "Rrs_547",
                "Remote sensing reflectance at band 555nm": "Rrs_555",
                "Remote sensing reflectance at band 645nm": "Rrs_645",
                "Remote sensing reflectance at band 667nm": "Rrs_667",
                "Remote sensing reflectance at band 678nm": "Rrs_678",
            }

            band_options = list(band_dict.keys())
            band = st.selectbox(
                "Select a band",
                band_options,
                band_options.index("Sea surface temperature"),
            )
            st.session_state["band"] = band_dict[band]

            colors = cm.list_colormaps()
            palette_options = st.selectbox(
                "Color palette",
                colors,
                index=colors.index("coolwarm"),
            )
            palette_values = cm.get_palette(palette_options, 15)
            palette = st.text_area(
                "Enter a custom palette:",
                palette_values,
            )
            st.write(cm.plot_colormap(cmap=palette_options, return_fig=True))
            st.session_state["palette"] = eval(palette)

        sample_roi = st.selectbox(
            "Select a sample ROI or upload a GeoJSON file:",
            roi_options,
            index=0,
        )

        add_outline = st.checkbox(
            "Overlay an administrative boundary on timelapse", False
        )

        if add_outline:

            with st.expander("Customize administrative boundary", True):

                overlay_options = {
                    "User-defined": None,
                    "Continents": "continents",
                    "Countries": "countries",
                    "US States": "us_states",
                    "China": "china",
                }

                overlay = st.selectbox(
                    "Select an administrative boundary:",
                    list(overlay_options.keys()),
                    index=2,
                )

                overlay_data = overlay_options[overlay]

                if overlay_data is None:
                    overlay_data = st.text_input(
                        "Enter an HTTP URL to a GeoJSON file or an ee.FeatureCollection asset id:",
                        "https://raw.githubusercontent.com/giswqs/geemap/master/examples/data/countries.geojson",
                    )

                overlay_color = st.color_picker(
                    "Select a color for the administrative boundary:", "#000000"
                )
                overlay_width = st.slider(
                    "Select a line width for the administrative boundary:", 1, 20, 1
                )
                overlay_opacity = st.slider(
                    "Select an opacity for the administrative boundary:",
                    0.0,
                    1.0,
                    1.0,
                    0.05,
                )
        else:
            overlay_data = None
            overlay_color = "black"
            overlay_width = 1
            overlay_opacity = 1

    with row1_col1:

        with st.expander(
            "Steps: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Expand this tab to see a demo 👉"
        ):
            video_empty = st.empty()

        data = st.file_uploader(
            "Upload a GeoJSON file to use as an ROI. Customize timelapse parameters and then click the Submit button 😇👇",
            type=["geojson", "kml", "zip"],
        )

        crs = "epsg:4326"
        if sample_roi == "Uploaded GeoJSON":
            if data is None:
                # st.info(
                #     "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click Submit button"
                # )
                if collection in [
                    "Geostationary Operational Environmental Satellites (GOES)",
                    "USDA National Agriculture Imagery Program (NAIP)",
                ] and (not keyword):
                    m.set_center(-100, 40, 3)
                # else:
                #     m.set_center(4.20, 18.63, zoom=2)
        else:
            if collection in [
                "Landsat TM-ETM-OLI Surface Reflectance",
                "Sentinel-2 MSI Surface Reflectance",
            ]:
                gdf = gpd.GeoDataFrame(
                    index=[0], crs=crs, geometry=[landsat_rois[sample_roi]]
                )
            elif (
                collection
                == "Geostationary Operational Environmental Satellites (GOES)"
            ):
                gdf = gpd.GeoDataFrame(
                    index=[0], crs=crs, geometry=[goes_rois[sample_roi]["region"]]
                )
            elif collection == "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km":
                gdf = gpd.GeoDataFrame(
                    index=[0], crs=crs, geometry=[modis_rois[sample_roi]]
                )

        if sample_roi != "Uploaded GeoJSON":

            if collection in [
                "Landsat TM-ETM-OLI Surface Reflectance",
                "Sentinel-2 MSI Surface Reflectance",
            ]:
                gdf = gpd.GeoDataFrame(
                    index=[0], crs=crs, geometry=[landsat_rois[sample_roi]]
                )
            elif (
                collection
                == "Geostationary Operational Environmental Satellites (GOES)"
            ):
                gdf = gpd.GeoDataFrame(
                    index=[0], crs=crs, geometry=[goes_rois[sample_roi]["region"]]
                )
            elif collection in [
                "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km",
                "MODIS Gap filled Land Surface Temperature Daily",
            ]:
                gdf = gpd.GeoDataFrame(
                    index=[0], crs=crs, geometry=[modis_rois[sample_roi]]
                )
            elif collection == "MODIS Ocean Color SMI":
                gdf = gpd.GeoDataFrame(
                    index=[0], crs=crs, geometry=[ocean_rois[sample_roi]]
                )
            st.session_state["roi"] = geemap.gdf_to_ee(gdf, geodesic=False)
            m.add_gdf(gdf, "ROI")

        elif data:
            gdf = uploaded_file_to_gdf(data)
            st.session_state["roi"] = geemap.gdf_to_ee(gdf, geodesic=False)
            m.add_gdf(gdf, "ROI")

        m.to_streamlit(height=600)

    with row1_col2:

        if collection in [
            "Landsat TM-ETM-OLI Surface Reflectance",
            "Sentinel-2 MSI Surface Reflectance",
        ]:

            if collection == "Landsat TM-ETM-OLI Surface Reflectance":
                sensor_start_year = 1984
                timelapse_title = "Landsat Timelapse"
                timelapse_speed = 5
            elif collection == "Sentinel-2 MSI Surface Reflectance":
                sensor_start_year = 2015
                timelapse_title = "Sentinel-2 Timelapse"
                timelapse_speed = 5
            video_empty.video("https://youtu.be/VVRK_-dEjR4")

            with st.form("submit_landsat_form"):

                roi = None
                if st.session_state.get("roi") is not None:
                    roi = st.session_state.get("roi")
                out_gif = geemap.temp_file_path(".gif")

                title = st.text_input(
                    "Enter a title to show on the timelapse: ", timelapse_title
                )
                RGB = st.selectbox(
                    "Select an RGB band combination:",
                    [
                        "Red/Green/Blue",
                        "NIR/Red/Green",
                        "SWIR2/SWIR1/NIR",
                        "NIR/SWIR1/Red",
                        "SWIR2/NIR/Red",
                        "SWIR2/SWIR1/Red",
                        "SWIR1/NIR/Blue",
                        "NIR/SWIR1/Blue",
                        "SWIR2/NIR/Green",
                        "SWIR1/NIR/Red",
                        "SWIR2/NIR/SWIR1",
                        "SWIR1/NIR/SWIR2",
                    ],
                    index=9,
                )

                frequency = st.selectbox(
                    "Select a temporal frequency:",
                    ["year", "quarter", "month"],
                    index=0,
                )

                with st.expander("Customize timelapse"):

                    speed = st.slider("Frames per second:", 1, 30, timelapse_speed)
                    dimensions = st.slider(
                        "Maximum dimensions (Width*Height) in pixels", 768, 2000, 768
                    )
                    progress_bar_color = st.color_picker(
                        "Progress bar color:", "#0000ff"
                    )
                    years = st.slider(
                        "Start and end year:",
                        sensor_start_year,
                        today.year,
                        (sensor_start_year, today.year),
                    )
                    months = st.slider("Start and end month:", 1, 12, (1, 12))
                    font_size = st.slider("Font size:", 10, 50, 30)
                    font_color = st.color_picker("Font color:", "#ffffff")
                    apply_fmask = st.checkbox(
                        "Apply fmask (remove clouds, shadows, snow)", True
                    )
                    font_type = st.selectbox(
                        "Select the font type for the title:",
                        ["arial.ttf", "alibaba.otf"],
                        index=0,
                    )
                    fading = st.slider(
                        "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
                    )
                    mp4 = st.checkbox("Save timelapse as MP4", True)

                empty_text = st.empty()
                empty_image = st.empty()
                empty_fire_image = st.empty()
                empty_video = st.container()
                submitted = st.form_submit_button("Submit")
                if submitted:

                    if sample_roi == "Uploaded GeoJSON" and data is None:
                        empty_text.warning(
                            "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
                        )
                    else:

                        empty_text.text("Computing... Please wait...")

                        start_year = years[0]
                        end_year = years[1]
                        start_date = str(months[0]).zfill(2) + "-01"
                        end_date = str(months[1]).zfill(2) + "-30"
                        bands = RGB.split("/")

                        try:
                            if collection == "Landsat TM-ETM-OLI Surface Reflectance":
                                out_gif = geemap.landsat_timelapse(
                                    roi=roi,
                                    out_gif=out_gif,
                                    start_year=start_year,
                                    end_year=end_year,
                                    start_date=start_date,
                                    end_date=end_date,
                                    bands=bands,
                                    apply_fmask=apply_fmask,
                                    frames_per_second=speed,
                                    dimensions=dimensions,
                                    overlay_data=overlay_data,
                                    overlay_color=overlay_color,
                                    overlay_width=overlay_width,
                                    overlay_opacity=overlay_opacity,
                                    frequency=frequency,
                                    date_format=None,
                                    title=title,
                                    title_xy=("2%", "90%"),
                                    add_text=True,
                                    text_xy=("2%", "2%"),
                                    text_sequence=None,
                                    font_type=font_type,
                                    font_size=font_size,
                                    font_color=font_color,
                                    add_progress_bar=True,
                                    progress_bar_color=progress_bar_color,
                                    progress_bar_height=5,
                                    loop=0,
                                    mp4=mp4,
                                    fading=fading,
                                )
                            elif collection == "Sentinel-2 MSI Surface Reflectance":
                                out_gif = geemap.sentinel2_timelapse(
                                    roi=roi,
                                    out_gif=out_gif,
                                    start_year=start_year,
                                    end_year=end_year,
                                    start_date=start_date,
                                    end_date=end_date,
                                    bands=bands,
                                    apply_fmask=apply_fmask,
                                    frames_per_second=speed,
                                    dimensions=dimensions,
                                    overlay_data=overlay_data,
                                    overlay_color=overlay_color,
                                    overlay_width=overlay_width,
                                    overlay_opacity=overlay_opacity,
                                    frequency=frequency,
                                    date_format=None,
                                    title=title,
                                    title_xy=("2%", "90%"),
                                    add_text=True,
                                    text_xy=("2%", "2%"),
                                    text_sequence=None,
                                    font_type=font_type,
                                    font_size=font_size,
                                    font_color=font_color,
                                    add_progress_bar=True,
                                    progress_bar_color=progress_bar_color,
                                    progress_bar_height=5,
                                    loop=0,
                                    mp4=mp4,
                                    fading=fading,
                                )
                        except:
                            empty_text.error(
                                "An error occurred while computing the timelapse. Your probably requested too much data. Try reducing the ROI or timespan."
                            )
                            st.stop()

                        if out_gif is not None and os.path.exists(out_gif):

                            empty_text.text(
                                "Right click the GIF to save it to your computer👇"
                            )
                            empty_image.image(out_gif)

                            out_mp4 = out_gif.replace(".gif", ".mp4")
                            if mp4 and os.path.exists(out_mp4):
                                with empty_video:
                                    st.text(
                                        "Right click the MP4 to save it to your computer👇"
                                    )
                                    st.video(out_gif.replace(".gif", ".mp4"))

                        else:
                            empty_text.error(
                                "Something went wrong. You probably requested too much data. Try reducing the ROI or timespan."
                            )

        elif collection == "Geostationary Operational Environmental Satellites (GOES)":

            video_empty.video("https://youtu.be/16fA2QORG4A")

            with st.form("submit_goes_form"):

                roi = None
                if st.session_state.get("roi") is not None:
                    roi = st.session_state.get("roi")
                out_gif = geemap.temp_file_path(".gif")

                satellite = st.selectbox("Select a satellite:", ["GOES-17", "GOES-16"])
                earliest_date = datetime.date(2017, 7, 10)
                latest_date = datetime.date.today()

                if sample_roi == "Uploaded GeoJSON":
                    roi_start_date = today - datetime.timedelta(days=2)
                    roi_end_date = today - datetime.timedelta(days=1)
                    roi_start_time = datetime.time(14, 00)
                    roi_end_time = datetime.time(1, 00)
                else:
                    roi_start = goes_rois[sample_roi]["start_time"]
                    roi_end = goes_rois[sample_roi]["end_time"]
                    roi_start_date = datetime.datetime.strptime(
                        roi_start[:10], "%Y-%m-%d"
                    )
                    roi_end_date = datetime.datetime.strptime(roi_end[:10], "%Y-%m-%d")
                    roi_start_time = datetime.time(
                        int(roi_start[11:13]), int(roi_start[14:16])
                    )
                    roi_end_time = datetime.time(
                        int(roi_end[11:13]), int(roi_end[14:16])
                    )

                start_date = st.date_input("Select the start date:", roi_start_date)
                end_date = st.date_input("Select the end date:", roi_end_date)

                with st.expander("Customize timelapse"):

                    add_fire = st.checkbox("Add Fire/Hotspot Characterization", False)

                    scan_type = st.selectbox(
                        "Select a scan type:", ["Full Disk", "CONUS", "Mesoscale"]
                    )

                    start_time = st.time_input(
                        "Select the start time of the start date:", roi_start_time
                    )

                    end_time = st.time_input(
                        "Select the end time of the end date:", roi_end_time
                    )

                    start = (
                        start_date.strftime("%Y-%m-%d")
                        + "T"
                        + start_time.strftime("%H:%M:%S")
                    )
                    end = (
                        end_date.strftime("%Y-%m-%d")
                        + "T"
                        + end_time.strftime("%H:%M:%S")
                    )

                    speed = st.slider("Frames per second:", 1, 30, 5)
                    add_progress_bar = st.checkbox("Add a progress bar", True)
                    progress_bar_color = st.color_picker(
                        "Progress bar color:", "#0000ff"
                    )
                    font_size = st.slider("Font size:", 10, 50, 20)
                    font_color = st.color_picker("Font color:", "#ffffff")
                    fading = st.slider(
                        "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
                    )
                    mp4 = st.checkbox("Save timelapse as MP4", True)

                empty_text = st.empty()
                empty_image = st.empty()
                empty_video = st.container()
                empty_fire_text = st.empty()
                empty_fire_image = st.empty()

                submitted = st.form_submit_button("Submit")
                if submitted:
                    if sample_roi == "Uploaded GeoJSON" and data is None:
                        empty_text.warning(
                            "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
                        )
                    else:
                        empty_text.text("Computing... Please wait...")

                        geemap.goes_timelapse(
                            out_gif,
                            start_date=start,
                            end_date=end,
                            data=satellite,
                            scan=scan_type.replace(" ", "_").lower(),
                            region=roi,
                            dimensions=768,
                            framesPerSecond=speed,
                            date_format="YYYY-MM-dd HH:mm",
                            xy=("3%", "3%"),
                            text_sequence=None,
                            font_type="arial.ttf",
                            font_size=font_size,
                            font_color=font_color,
                            add_progress_bar=add_progress_bar,
                            progress_bar_color=progress_bar_color,
                            progress_bar_height=5,
                            loop=0,
                            overlay_data=overlay_data,
                            overlay_color=overlay_color,
                            overlay_width=overlay_width,
                            overlay_opacity=overlay_opacity,
                            mp4=mp4,
                            fading=fading,
                        )

                        if out_gif is not None and os.path.exists(out_gif):
                            empty_text.text(
                                "Right click the GIF to save it to your computer👇"
                            )
                            empty_image.image(out_gif)

                            out_mp4 = out_gif.replace(".gif", ".mp4")
                            if mp4 and os.path.exists(out_mp4):
                                with empty_video:
                                    st.text(
                                        "Right click the MP4 to save it to your computer👇"
                                    )
                                    st.video(out_gif.replace(".gif", ".mp4"))

                            if add_fire:
                                out_fire_gif = geemap.temp_file_path(".gif")
                                empty_fire_text.text(
                                    "Delineating Fire Hotspot... Please wait..."
                                )
                                geemap.goes_fire_timelapse(
                                    out_fire_gif,
                                    start_date=start,
                                    end_date=end,
                                    data=satellite,
                                    scan=scan_type.replace(" ", "_").lower(),
                                    region=roi,
                                    dimensions=768,
                                    framesPerSecond=speed,
                                    date_format="YYYY-MM-dd HH:mm",
                                    xy=("3%", "3%"),
                                    text_sequence=None,
                                    font_type="arial.ttf",
                                    font_size=font_size,
                                    font_color=font_color,
                                    add_progress_bar=add_progress_bar,
                                    progress_bar_color=progress_bar_color,
                                    progress_bar_height=5,
                                    loop=0,
                                )
                                if os.path.exists(out_fire_gif):
                                    empty_fire_image.image(out_fire_gif)
                        else:
                            empty_text.text(
                                "Something went wrong, either the ROI is too big or there are no data available for the specified date range. Please try a smaller ROI or different date range."
                            )

        elif collection == "MODIS Vegetation Indices (NDVI/EVI) 16-Day Global 1km":

            video_empty.video("https://youtu.be/16fA2QORG4A")

            satellite = st.selectbox("Select a satellite:", ["Terra", "Aqua"])
            band = st.selectbox("Select a band:", ["NDVI", "EVI"])

            with st.form("submit_modis_form"):

                roi = None
                if st.session_state.get("roi") is not None:
                    roi = st.session_state.get("roi")
                out_gif = geemap.temp_file_path(".gif")

                with st.expander("Customize timelapse"):

                    start = st.date_input(
                        "Select a start date:", datetime.date(2000, 2, 8)
                    )
                    end = st.date_input("Select an end date:", datetime.date.today())

                    start_date = start.strftime("%Y-%m-%d")
                    end_date = end.strftime("%Y-%m-%d")

                    speed = st.slider("Frames per second:", 1, 30, 5)
                    add_progress_bar = st.checkbox("Add a progress bar", True)
                    progress_bar_color = st.color_picker(
                        "Progress bar color:", "#0000ff"
                    )
                    font_size = st.slider("Font size:", 10, 50, 20)
                    font_color = st.color_picker("Font color:", "#ffffff")

                    font_type = st.selectbox(
                        "Select the font type for the title:",
                        ["arial.ttf", "alibaba.otf"],
                        index=0,
                    )
                    fading = st.slider(
                        "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
                    )
                    mp4 = st.checkbox("Save timelapse as MP4", True)

                empty_text = st.empty()
                empty_image = st.empty()
                empty_video = st.container()

                submitted = st.form_submit_button("Submit")
                if submitted:
                    if sample_roi == "Uploaded GeoJSON" and data is None:
                        empty_text.warning(
                            "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
                        )
                    else:

                        empty_text.text("Computing... Please wait...")

                        geemap.modis_ndvi_timelapse(
                            out_gif,
                            satellite,
                            band,
                            start_date,
                            end_date,
                            roi,
                            768,
                            speed,
                            overlay_data=overlay_data,
                            overlay_color=overlay_color,
                            overlay_width=overlay_width,
                            overlay_opacity=overlay_opacity,
                            mp4=mp4,
                            fading=fading,
                        )

                        geemap.reduce_gif_size(out_gif)

                        empty_text.text(
                            "Right click the GIF to save it to your computer👇"
                        )
                        empty_image.image(out_gif)

                        out_mp4 = out_gif.replace(".gif", ".mp4")
                        if mp4 and os.path.exists(out_mp4):
                            with empty_video:
                                st.text(
                                    "Right click the MP4 to save it to your computer👇"
                                )
                                st.video(out_gif.replace(".gif", ".mp4"))

        elif collection == "Any Earth Engine ImageCollection":

            with st.form("submit_ts_form"):
                with st.expander("Customize timelapse"):

                    title = st.text_input(
                        "Enter a title to show on the timelapse: ", "Timelapse"
                    )
                    start_date = st.date_input(
                        "Select the start date:", datetime.date(2020, 1, 1)
                    )
                    end_date = st.date_input(
                        "Select the end date:", datetime.date.today()
                    )
                    frequency = st.selectbox(
                        "Select a temporal frequency:",
                        ["year", "quarter", "month", "day", "hour", "minute", "second"],
                        index=0,
                    )
                    reducer = st.selectbox(
                        "Select a reducer for aggregating data:",
                        ["median", "mean", "min", "max", "sum", "variance", "stdDev"],
                        index=0,
                    )
                    data_format = st.selectbox(
                        "Select a date format to show on the timelapse:",
                        [
                            "YYYY-MM-dd",
                            "YYYY",
                            "YYMM-MM",
                            "YYYY-MM-dd HH:mm",
                            "YYYY-MM-dd HH:mm:ss",
                            "HH:mm",
                            "HH:mm:ss",
                            "w",
                            "M",
                            "d",
                            "D",
                        ],
                        index=0,
                    )

                    speed = st.slider("Frames per second:", 1, 30, 5)
                    add_progress_bar = st.checkbox("Add a progress bar", True)
                    progress_bar_color = st.color_picker(
                        "Progress bar color:", "#0000ff"
                    )
                    font_size = st.slider("Font size:", 10, 50, 30)
                    font_color = st.color_picker("Font color:", "#ffffff")
                    font_type = st.selectbox(
                        "Select the font type for the title:",
                        ["arial.ttf", "alibaba.otf"],
                        index=0,
                    )
                    fading = st.slider(
                        "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
                    )
                    mp4 = st.checkbox("Save timelapse as MP4", True)

                empty_text = st.empty()
                empty_image = st.empty()
                empty_video = st.container()
                empty_fire_image = st.empty()

                roi = None
                if st.session_state.get("roi") is not None:
                    roi = st.session_state.get("roi")
                out_gif = geemap.temp_file_path(".gif")

                submitted = st.form_submit_button("Submit")
                if submitted:

                    if sample_roi == "Uploaded GeoJSON" and data is None:
                        empty_text.warning(
                            "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
                        )
                    else:

                        empty_text.text("Computing... Please wait...")
                        try:
                            geemap.create_timelapse(
                                st.session_state.get("ee_asset_id"),
                                start_date=start_date.strftime("%Y-%m-%d"),
                                end_date=end_date.strftime("%Y-%m-%d"),
                                region=roi,
                                frequency=frequency,
                                reducer=reducer,
                                date_format=data_format,
                                out_gif=out_gif,
                                bands=st.session_state.get("bands"),
                                palette=st.session_state.get("palette"),
                                vis_params=st.session_state.get("vis_params"),
                                dimensions=768,
                                frames_per_second=speed,
                                crs="EPSG:3857",
                                overlay_data=overlay_data,
                                overlay_color=overlay_color,
                                overlay_width=overlay_width,
                                overlay_opacity=overlay_opacity,
                                title=title,
                                title_xy=("2%", "90%"),
                                add_text=True,
                                text_xy=("2%", "2%"),
                                text_sequence=None,
                                font_type=font_type,
                                font_size=font_size,
                                font_color=font_color,
                                add_progress_bar=add_progress_bar,
                                progress_bar_color=progress_bar_color,
                                progress_bar_height=5,
                                loop=0,
                                mp4=mp4,
                                fading=fading,
                            )
                        except:
                            empty_text.error(
                                "An error occurred while computing the timelapse. You probably requested too much data. Try reducing the ROI or timespan."
                            )

                        empty_text.text(
                            "Right click the GIF to save it to your computer👇"
                        )
                        empty_image.image(out_gif)

                        out_mp4 = out_gif.replace(".gif", ".mp4")
                        if mp4 and os.path.exists(out_mp4):
                            with empty_video:
                                st.text(
                                    "Right click the MP4 to save it to your computer👇"
                                )
                                st.video(out_gif.replace(".gif", ".mp4"))

        elif collection in [
            "MODIS Gap filled Land Surface Temperature Daily",
            "MODIS Ocean Color SMI",
        ]:

            with st.form("submit_ts_form"):
                with st.expander("Customize timelapse"):

                    title = st.text_input(
                        "Enter a title to show on the timelapse: ",
                        "Surface Temperature",
                    )
                    start_date = st.date_input(
                        "Select the start date:", datetime.date(2018, 1, 1)
                    )
                    end_date = st.date_input(
                        "Select the end date:", datetime.date(2020, 12, 31)
                    )
                    frequency = st.selectbox(
                        "Select a temporal frequency:",
                        ["year", "quarter", "month", "week", "day"],
                        index=2,
                    )
                    reducer = st.selectbox(
                        "Select a reducer for aggregating data:",
                        ["median", "mean", "min", "max", "sum", "variance", "stdDev"],
                        index=0,
                    )

                    vis_params = st.text_area(
                        "Enter visualization parameters",
                        "",
                        help="Enter a string in the format of a dictionary, such as '{'min': 23, 'max': 32}'",
                    )

                    speed = st.slider("Frames per second:", 1, 30, 5)
                    add_progress_bar = st.checkbox("Add a progress bar", True)
                    progress_bar_color = st.color_picker(
                        "Progress bar color:", "#0000ff"
                    )
                    font_size = st.slider("Font size:", 10, 50, 30)
                    font_color = st.color_picker("Font color:", "#ffffff")
                    font_type = st.selectbox(
                        "Select the font type for the title:",
                        ["arial.ttf", "alibaba.otf"],
                        index=0,
                    )
                    add_colorbar = st.checkbox("Add a colorbar", True)
                    colorbar_label = st.text_input(
                        "Enter the colorbar label:", "Surface Temperature (°C)"
                    )
                    fading = st.slider(
                        "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
                    )
                    mp4 = st.checkbox("Save timelapse as MP4", True)

                empty_text = st.empty()
                empty_image = st.empty()
                empty_video = st.container()

                roi = None
                if st.session_state.get("roi") is not None:
                    roi = st.session_state.get("roi")
                out_gif = geemap.temp_file_path(".gif")

                submitted = st.form_submit_button("Submit")
                if submitted:

                    if sample_roi == "Uploaded GeoJSON" and data is None:
                        empty_text.warning(
                            "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
                        )
                    else:

                        empty_text.text("Computing... Please wait...")
                        try:
                            if (
                                collection
                                == "MODIS Gap filled Land Surface Temperature Daily"
                            ):
                                out_gif = geemap.create_timelapse(
                                    st.session_state.get("ee_asset_id"),
                                    start_date=start_date.strftime("%Y-%m-%d"),
                                    end_date=end_date.strftime("%Y-%m-%d"),
                                    region=roi,
                                    bands=None,
                                    frequency=frequency,
                                    reducer=reducer,
                                    date_format=None,
                                    out_gif=out_gif,
                                    palette=st.session_state.get("palette"),
                                    vis_params=None,
                                    dimensions=768,
                                    frames_per_second=speed,
                                    crs="EPSG:3857",
                                    overlay_data=overlay_data,
                                    overlay_color=overlay_color,
                                    overlay_width=overlay_width,
                                    overlay_opacity=overlay_opacity,
                                    title=title,
                                    title_xy=("2%", "90%"),
                                    add_text=True,
                                    text_xy=("2%", "2%"),
                                    text_sequence=None,
                                    font_type=font_type,
                                    font_size=font_size,
                                    font_color=font_color,
                                    add_progress_bar=add_progress_bar,
                                    progress_bar_color=progress_bar_color,
                                    progress_bar_height=5,
                                    add_colorbar=add_colorbar,
                                    colorbar_label=colorbar_label,
                                    loop=0,
                                    mp4=mp4,
                                    fading=fading,
                                )
                            elif collection == "MODIS Ocean Color SMI":
                                if vis_params.startswith("{") and vis_params.endswith(
                                    "}"
                                ):
                                    vis_params = eval(vis_params)
                                else:
                                    vis_params = None
                                out_gif = geemap.modis_ocean_color_timelapse(
                                    st.session_state.get("ee_asset_id"),
                                    start_date=start_date.strftime("%Y-%m-%d"),
                                    end_date=end_date.strftime("%Y-%m-%d"),
                                    region=roi,
                                    bands=st.session_state["band"],
                                    frequency=frequency,
                                    reducer=reducer,
                                    date_format=None,
                                    out_gif=out_gif,
                                    palette=st.session_state.get("palette"),
                                    vis_params=vis_params,
                                    dimensions=768,
                                    frames_per_second=speed,
                                    crs="EPSG:3857",
                                    overlay_data=overlay_data,
                                    overlay_color=overlay_color,
                                    overlay_width=overlay_width,
                                    overlay_opacity=overlay_opacity,
                                    title=title,
                                    title_xy=("2%", "90%"),
                                    add_text=True,
                                    text_xy=("2%", "2%"),
                                    text_sequence=None,
                                    font_type=font_type,
                                    font_size=font_size,
                                    font_color=font_color,
                                    add_progress_bar=add_progress_bar,
                                    progress_bar_color=progress_bar_color,
                                    progress_bar_height=5,
                                    add_colorbar=add_colorbar,
                                    colorbar_label=colorbar_label,
                                    loop=0,
                                    mp4=mp4,
                                    fading=fading,
                                )
                        except:
                            empty_text.error(
                                "Something went wrong. You probably requested too much data. Try reducing the ROI or timespan."
                            )

                        if out_gif is not None and os.path.exists(out_gif):

                            geemap.reduce_gif_size(out_gif)

                            empty_text.text(
                                "Right click the GIF to save it to your computer👇"
                            )
                            empty_image.image(out_gif)

                            out_mp4 = out_gif.replace(".gif", ".mp4")
                            if mp4 and os.path.exists(out_mp4):
                                with empty_video:
                                    st.text(
                                        "Right click the MP4 to save it to your computer👇"
                                    )
                                    st.video(out_gif.replace(".gif", ".mp4"))

                        else:
                            st.error(
                                "Something went wrong. You probably requested too much data. Try reducing the ROI or timespan."
                            )

        elif collection == "USDA National Agriculture Imagery Program (NAIP)":

            with st.form("submit_naip_form"):
                with st.expander("Customize timelapse"):

                    title = st.text_input(
                        "Enter a title to show on the timelapse: ", "NAIP Timelapse"
                    )

                    years = st.slider(
                        "Start and end year:",
                        2003,
                        today.year,
                        (2003, today.year),
                    )

                    bands = st.selectbox(
                        "Select a band combination:", ["N/R/G", "R/G/B"], index=0
                    )

                    speed = st.slider("Frames per second:", 1, 30, 3)
                    add_progress_bar = st.checkbox("Add a progress bar", True)
                    progress_bar_color = st.color_picker(
                        "Progress bar color:", "#0000ff"
                    )
                    font_size = st.slider("Font size:", 10, 50, 30)
                    font_color = st.color_picker("Font color:", "#ffffff")
                    font_type = st.selectbox(
                        "Select the font type for the title:",
                        ["arial.ttf", "alibaba.otf"],
                        index=0,
                    )
                    fading = st.slider(
                        "Fading duration (seconds) for each frame:", 0.0, 3.0, 0.0
                    )
                    mp4 = st.checkbox("Save timelapse as MP4", True)

                empty_text = st.empty()
                empty_image = st.empty()
                empty_video = st.container()
                empty_fire_image = st.empty()

                roi = None
                if st.session_state.get("roi") is not None:
                    roi = st.session_state.get("roi")
                out_gif = geemap.temp_file_path(".gif")

                submitted = st.form_submit_button("Submit")
                if submitted:

                    if sample_roi == "Uploaded GeoJSON" and data is None:
                        empty_text.warning(
                            "Steps to create a timelapse: Draw a rectangle on the map -> Export it as a GeoJSON -> Upload it back to the app -> Click the Submit button. Alternatively, you can select a sample ROI from the dropdown list."
                        )
                    else:

                        empty_text.text("Computing... Please wait...")
                        try:
                            geemap.naip_timelapse(
                                roi,
                                years[0],
                                years[1],
                                out_gif,
                                bands=bands.split("/"),
                                palette=st.session_state.get("palette"),
                                vis_params=None,
                                dimensions=768,
                                frames_per_second=speed,
                                crs="EPSG:3857",
                                overlay_data=overlay_data,
                                overlay_color=overlay_color,
                                overlay_width=overlay_width,
                                overlay_opacity=overlay_opacity,
                                title=title,
                                title_xy=("2%", "90%"),
                                add_text=True,
                                text_xy=("2%", "2%"),
                                text_sequence=None,
                                font_type=font_type,
                                font_size=font_size,
                                font_color=font_color,
                                add_progress_bar=add_progress_bar,
                                progress_bar_color=progress_bar_color,
                                progress_bar_height=5,
                                loop=0,
                                mp4=mp4,
                                fading=fading,
                            )
                        except:
                            empty_text.error(
                                "Something went wrong. You either requested too much data or the ROI is outside the U.S."
                            )

                        if out_gif is not None and os.path.exists(out_gif):

                            empty_text.text(
                                "Right click the GIF to save it to your computer👇"
                            )
                            empty_image.image(out_gif)

                            out_mp4 = out_gif.replace(".gif", ".mp4")
                            if mp4 and os.path.exists(out_mp4):
                                with empty_video:
                                    st.text(
                                        "Right click the MP4 to save it to your computer👇"
                                    )
                                    st.video(out_gif.replace(".gif", ".mp4"))

                        else:
                            st.error(
                                "Something went wrong. You either requested too much data or the ROI is outside the U.S."
                            )