File size: 32,576 Bytes
646cbcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import requests
import json
import os
from PIL import Image
import moviepy.video.io.ImageSequenceClip as ic
#from datetime import date, timedelta

from pathlib import Path
import bs4
import datetime
import urllib.request 
import uuid
import base64
import os
#print(os.system('pip freeze'))
main_directory = "https://services.swpc.noaa.gov/"
sdo_source = "https://sdo.gsfc.nasa.gov/assets/img/browse/"
sdo_source_format = "https://sdo.gsfc.nasa.gov/assets/img/browse/YEAR/MONTH/DAY/DATE_IDENT_SIZE_TOOL.jpg"

comp_list=[
    "https://services.swpc.noaa.gov/images/geospace/geospace_1_day.png",
    "https://services.swpc.noaa.gov/images/ace-epam-24-hour.gif",
    "https://services.swpc.noaa.gov/images/ace-epam-e-24-hour.gif",
    "https://services.swpc.noaa.gov/images/ace-epam-p-24-hour.gif",
    "https://services.swpc.noaa.gov/images/ace-mag-24-hour.gif",
    "https://services.swpc.noaa.gov/images/ace-mag-swepam-24-hour.gif",
    "https://services.swpc.noaa.gov/images/ace-sis-24-hour.gif",
    "https://services.swpc.noaa.gov/images/boulder-magnetometer.png",
    "https://services.swpc.noaa.gov/images/seaesrt-time-series-270.png",
    "https://services.swpc.noaa.gov/images/station-k-index.png",
    #"https://services.swpc.noaa.gov/images/swx-overview-large.gif",
    "https://services.swpc.noaa.gov/images/notifications-timeline.png",
]

sdo_aia_latest=[
    {"name":"Fe18 94A", "source":"https://umbra.nascom.nasa.gov/images/latest_aia_94.gif"},
    {"name":"Fe20 131A", "source":"https://umbra.nascom.nasa.gov/images/latest_aia_131.gif"},
    {"name":"Fe9/10 171A", "source":"https://umbra.nascom.nasa.gov/images/latest_aia_171.gif"},
    {"name":"Fe12 193A", "source":"https://umbra.nascom.nasa.gov/images/latest_aia_193.gif"},
    
    {"name":"Fe14 211A", "source":"https://umbra.nascom.nasa.gov/images/latest_aia_211.gif"},
    {"name":"He2 304A", "source":"https://umbra.nascom.nasa.gov/images/latest_aia_304.gif"},
    {"name":"Fe16 335A", "source":"https://umbra.nascom.nasa.gov/images/latest_aia_335.gif"},
    {"name":"cont+C4 1600A", "source":"https://umbra.nascom.nasa.gov/images/latest_aia_1600.gif"},
    {"name":"continuum 1700A", "source":"https://umbra.nascom.nasa.gov/images/latest_aia_1700.gif"},
    {"name":"continuum 4500A", "source":"https://umbra.nascom.nasa.gov/images/latest_aia_4500.gif"},
]

nasa_images=[
    {"name":"EIT 171A", "source":"https://soho.nascom.nasa.gov/data/realtime/eit_171/512/latest.jpg"},
    {"name":"EIT 195A", "source":"https://soho.nascom.nasa.gov/data/realtime/eit_195/512/latest.jpg"},
    {"name":"EIT 284A", "source":"https://soho.nascom.nasa.gov/data/realtime/eit_284/512/latest.jpg"},
    {"name":"EIT 304A", "source":"https://soho.nascom.nasa.gov/data/realtime/eit_304/512/latest.jpg"},
]

nasa_soho_gifs=[
    {"name":"EIT 304A", "source":"https://soho.nascom.nasa.gov/data/LATEST/current_eit_304small.gif"},
    {"name":"EIT 195A", "source":"https://soho.nascom.nasa.gov/data/LATEST/current_eit_195small.gif"},
    {"name":"EIT 171A", "source":"https://soho.nascom.nasa.gov/data/LATEST/current_eit_171small.gif"},
    {"name":"EIT 284A", "source":"https://soho.nascom.nasa.gov/data/LATEST/current_eit_284small.gif"},
]    
nasa_soho_mp4=[
    {"name":"EIT 171A", "source":"https://soho.nascom.nasa.gov/data/LATEST/current_eit_171small.mp4"},
    {"name":"EIT 195A", "source":"https://soho.nascom.nasa.gov/data/LATEST/current_eit_195small.mp4"},
    {"name":"EIT 284A", "source":"https://soho.nascom.nasa.gov/data/LATEST/current_eit_284small.mp4"},
    {"name":"EIT 304A", "source":"https://soho.nascom.nasa.gov/data/LATEST/current_eit_304small.mp4"},
    
    {"name":"LASCO C2", "source":"https://soho.nascom.nasa.gov/data/LATEST/current_c2small.mp4"},
    {"name":"LASCO C3", "source":"https://soho.nascom.nasa.gov/data/LATEST/current_c3small.mp4"},
    {"name":"SDO/HMI Continuum", "source":"https://soho.nascom.nasa.gov/data/LATEST/current_hmi_igr-512.mp4"},
    {"name":"SDO/HMI Magnetogram", "source":"https://soho.nascom.nasa.gov/data/LATEST/current_hmi_mag-512.mp4"},
]  

sdo_obj = ["HMIB","HMIBC","HMIIC","HMIIF","HMID","HMII","HMI171",
           "0094","0131","0171","0193","0211",
           "0304","0335","1600","1700","4500",
           "211193171","211193171n","211193171rg",
           "094335193","304211171"]
sdo_size= [256,512,1024,2048,4096]
month_dict={"01":31,"02":28,"03":31,"04":30,"05":31,"06":30,"07":31,"08":31,"09":30,"10":31,"11":30,"12":31}
html = """
<div>
PAGE_LINK
</div>
"""
css="""
.img_box{
    display: flex;
    flex-direction: column;
    flex-flow: unset;
    flex-wrap: wrap;
    justify-content: space-around;
}
.img_class{
    background: #ffffff;
    max-width: 48%;
    font-family: monospace;
    border-top: #9300ff;
    border-style: inset;
    margin-top: 5px;
}
.img_class_raw{
    background: #ffffff;
    width: 100%;
    font-family: monospace;
    border-top: #9300ff;
    border-style: inset;
    margin-top: 5px;
    display:flex;
    flex-direction:column;
}
.img_box_soho{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
}
.img_class_soho{
    background: #ffffff;
    font-family: monospace;
    border-top: #9300ff;
    border-style: inset;
    margin-top: 5px;
    max-width: 48%;
}
.img_class_sdo{
    background: #ffffff;
    font-family: monospace;
    border-top: #9300ff;
    border-style: inset;
    margin-top: 5px;
    max-width: 25%;
    font-size: small;
}
"""
def load_json(url1="",url2="",url3="",url4="",url5="",url6="",url7="",url8=""):
    get_url=f'{main_directory}{url1}{url2}{url3}{url4}{url5}{url6}{url7}{url8}'
    print(f'{get_url}')
    get_url=get_url.split("None")[0]
    print(f'{get_url}')
    get_url=get_url.split("[]")[0]
    print(f'{get_url}')
    
    if get_url.endswith('.json'):
        feed1 = requests.get(get_url)
        return None, feed1.text
    elif get_url.endswith(".png") or get_url.endswith(".gif") or get_url.endswith(".jpg"):
        html_out=f"<style>{css}</style><div>"
        html_out+=f'<div class="img_class_raw"><a href="{get_url}" target="_blank">{get_url}</a><br><img src={get_url}></div></div>'
        return html_out, None
    return None,None
    
def make_tree(url1="",url2="",url3="",url4="",url5="",url6="",url7="",url8=""):
    link_box=[]
    html_out=""
    get_url=f'{main_directory}{url1}{url2}{url3}{url4}{url5}{url6}{url7}{url8}'
    print(f'######### :: {get_url}')
    if not get_url.endswith('.json'):
        feed1 = requests.get(get_url)
        spl = feed1.text.split("href=")
        for line in spl:
            spl2 = line.split(">")[0]
            #print(spl2)
            if spl2.endswith('/"') or spl2.endswith('.json"') or spl2.endswith('.png"') or spl2.endswith('.gif"') or spl2.endswith('.jpg"'):
                fin=line.split(">")[0].strip('""')
                link_box.append(fin)
                #html_out=html_out+html.replace("PAGE_LINK",fin)
        return gr.update(choices=[l for l in link_box],interactive=True)
    else:
        return None

def get_images():
    html_out=f"<style>{css}</style><div class='img_box'>"    
    get_url=f'{main_directory}images/geospace/'
    feed1 = requests.get(get_url)
    spl = feed1.text.split("href=")
    for line in spl:
        spl2 = line.split(">")[0].strip('""')
        if spl2.endswith(".png") or spl2.endswith(".gif") or spl2.endswith(".jpg"):
            #print(spl2)
            html_out+=f'<div class="img_class"><a href="{get_url}{spl2}" target="_blank">{spl2}</a><br><img src={get_url}{spl2}></div>'
        else:
            print(spl2)
    get_url2=f'{main_directory}images/'
    feed2 = requests.get(get_url2)
    spl = feed2.text.split("href=")
    for line2 in spl:
        spl2 = line2.split(">")[0].strip('""')
        if spl2.endswith(".png") or spl2.endswith(".gif") or spl2.endswith(".jpg"):
            #print(spl2)
            html_out+=f'<div class="img_class"><a href="{get_url2}{spl2}" target="_blank">{spl2}</a><br><img src={get_url2}{spl2}></div>'
        else:
            print(spl2)            
    html_out+="</div>"
    return html_out

def make_animation():
    get_url=f'{main_directory}images/animations/'
    feed1 = requests.get(get_url)
    spl = feed1.text.split("href=")
    files_out=[]
    for line in spl:
        gif_box=[]

        spl2 = line.split(">")[0].strip('""')
        if spl2.endswith("/"):
            feed2 = requests.get(f'{get_url}{spl2}')
            spl3 = feed2.text.split("href=")
            for line2 in spl3:
                spl3 = line2.split(">")[0].strip('""')
                print("$$$$$$$$$$$$$$")
                print(spl3)
                if spl3.endswith(".png") or spl3.endswith(".gif") or spl3.endswith(".jpg"):
                    gif_box.append(f'{get_url}{spl2}{spl3}')
            if gif_box:
                try:
                    #frames = [Image.open(image) for image in glob.glob(f"{frame_folder}/*.JPG")]
                    frames = []
                    for i,ea in enumerate(gif_box):
                        print("############")
                        print(ea)
                        urllib.request.urlretrieve(ea,f'tmp{i}.png')                     
                        frames.append(f'tmp{i}.png')
                    fps=60
                    uid=uuid.uuid4()
                    clip = ic.ImageSequenceClip(frames, fps = fps) 
                    clip.to_gif(f"{uid}.gif",fps=fps) 
                    files_out.append(f'{uid}.gif')
                except Exception as e:
                    print(e)
    return files_out


def make_animation_new(gif_box=[]):

    if gif_box:
        print(gif_box)
        gif_box.sort(reverse=False)
        print("Making GIF...")
        try:
            #frames = [Image.open(image) for image in glob.glob(f"{frame_folder}/*.JPG")]
            frames = []
            for i,ea in enumerate(gif_box):
                print("############")
                print(ea)
                urllib.request.urlretrieve(ea,f'tmp{i}.png')                     
                frames.append(f'tmp{i}.png')
            fps=60
            uid=uuid.uuid4()
            clip = ic.ImageSequenceClip(frames, fps = fps)


            # Save GIF to a temporary file
            temp_gif_path = f"temp_{uid}.gif"
            clip.write_gif(temp_gif_path, fps=fps)

            # Read the GIF file into bytes
            with open(temp_gif_path, 'rb') as gif_file:
                gif_bytes = gif_file.read()

            # Encode GIF bytes as base64 for HTML
            gif_base64 = base64.b64encode(gif_bytes).decode('utf-8')
            gif_data_url = f"data:image/gif;base64,{gif_base64}"

            
            html_out=f"<style>{css}</style><div>"
            html_out+=f'<div class="img_class"><img src="{gif_data_url}"></div>'
            html_out+="</div>"
            return html_out

        except Exception as e:
            print("ERROR HAPPENED")
            print(e)

    else:
        print("passed")

def make_html(inp_files):
    html_out=f"<style>{css}</style><div class='img_box'>"
    for ea in inp_files:
        print(ea)
        html_out+=f'<div class="img_class"><img src="file={ea}"></div>'
    html_out+='</div>'
    return html_out

def make_nasa_soho_videos():
    html_out=f"<style>{css}</style><div class='img_box_soho'>"
    for ea in nasa_soho_mp4:
        file_name=ea['source']
        html_out+=f'''
        <video width="50%" height="320" controls>
          <source src="{file_name}" type="video/mp4">
            Your browser does not support the video tag.
        </video>'''
        #html_out+=f'<div class="img_class_soho"><img src="file={file_name}"></div>'
    html_out+='</div>'
    return html_out
    
def make_nasa_soho_images(inp_src: list):
    html_out=""
    #html_out=f"<style>{css}</style><div class='img_box_soho'>"
    for ea in inp_src:
        file_name=ea['source']
        html_out+=f'<div class="img_class_soho"><img src="{file_name}"></div>'
    #html_out+='</div>'
    #html_out+=html_in
    return html_out    
def make_nasa_soho_image_trigger():
    html_in=f"<style>{css}</style><div class='img_box_soho'>"
    
    html_in+= make_nasa_soho_images(nasa_images)    
    html_in+= make_nasa_soho_images(sdo_aia_latest)     
    #html_in+= make_nasa_soho_videos()
    html_in+="</div>"
    return html_in
#from datetime import date, timedelta, datetime

def generate_sdo_urls(date1_str: str, date2_str: str) -> list[str]:
    """
    Generates a list of SDO browse image URLs for all days
    inclusive of date1_str and date2_str.

    The URL format is assumed to be:
    https://sdo.gsfc.nasa.gov/assets/img/browse/YYYY/MM/DD/

    Args:
        date1_str: Start date in "YYYYMMDD" format (e.g., "20230115").
        date2_str: End date in "YYYYMMDD" format (e.g., "20230117").

    Returns:
        A list of URL strings.
        Returns an empty list if date1_str > date2_str or if dates are invalid.
    """
    url_box = []
    base_url = "https://sdo.gsfc.nasa.gov/assets/img/browse"

    try:
        # Convert input strings to date objects
        # datetime.strptime creates a datetime object, .date() gets just the date part
        start_date = datetime.datetime.strptime(date1_str[:8], "%Y%m%d").date()
        end_date = datetime.datetime.strptime(date2_str[:8], "%Y%m%d").date()
    except ValueError:
        print(f"Error: Invalid date format. Please use YYYYMMDD. Received: '{date1_str}', '{date2_str}'")
        return [] # Return empty list for invalid date format

    # Handle cases where start_date is after end_date
    if start_date > end_date:
        print(f"Warning: Start date ({date1_str}) is after end date ({date2_str}). Returning an empty list.")
        return []

    current_date = start_date
    while current_date <= end_date:
        # Format year, month, and day with leading zeros if necessary
        # .year, .month, .day are integers
        year_str = f"{current_date.year:04}"  # Ensures YYYY format (though usually not needed for year)
        month_str = f"{current_date.month:02}" # Ensures MM format (e.g., 1 -> 01)
        day_str = f"{current_date.day:02}"   # Ensures DD format (e.g., 5 -> 05)

        # Construct the URL
        out_url = f"{base_url}/{year_str}/{month_str}/{day_str}/"
        url_box.append(out_url)

        # Move to the next day
        current_date += datetime.timedelta(days=1)

    return url_box


def count_days_og(date1,date2):
    url_box=[]
    in_year=f"{date1[0:4]}"
    in_month=f"{date1[4:6]}"
    in_day=f"{date1[6:8]}"
    
    end_year=f"{date2[0:4]}"
    end_month=f"{date2[4:6]}"
    end_day=f"{date2[6:8]}"

    years_rem,months_rem,days_rem=(0,0,0)
    og_days_rem=days_rem
    i_in_year,i_in_month,i_in_day,i_end_year,i_end_month,i_end_day=int(in_year),int(in_month),int(in_day),int(end_year),int(end_month),int(end_day)
    days_json={"year": 0, "month": 0, "day": 0}
    if i_end_year > i_in_year:
        years_rem = i_end_year-i_in_year
    if i_end_month > i_in_month:
        months_rem = 12 - i_in_month
    if i_end_day > i_in_day:
        og_days_rem = month_dict[in_month] - i_in_day
        
    if years_rem > 0:
        for ii in list(range(0,years_raw)):
            months_rem+=years_rem*12
            out_year = in_year+ii
            for i in list(range(0,months_rem)):
                month_day_cnt = month_dict[str(int(in_month)+i)]
                for io in list(range(0,month_day_cnt)):
                    days_rem += month_day_cnt
                    out_url=f"https://sdo.gsfc.nasa.gov/assets/img/browse/{out_year}/{i}/{io}/"
                    print(out_url)
                    url_box.append(out_url)
        months_raw = 0
    if months_rem > 0:
        out_year = in_year
        for i in list(range(0,months_rem)):
            month_day_cnt = month_dict[str(int(in_month)+i)]
            for io in list(range(0,month_day_cnt)):
                days_rem += month_day_cnt
                out_url=f"https://sdo.gsfc.nasa.gov/assets/img/browse/{out_year}/{i}/{io}/"
                print(out_url)
                url_box.append(out_url)
        og_days_rem=0
    if og_days_rem > 0:
        for io in list(range(0,og_days_rem)):
            days_rem += month_day_cnt
            out_url=f"https://sdo.gsfc.nasa.gov/assets/img/browse/{end_year}/{end_month}/{io}/"
            print(out_url)
            url_box.append(out_url)

    
def nasa_sdo_images(obj,size,date1,date2):
    url_box=[]
    html_in=f"<style>{css}</style><div class='img_box_soho'>"
    print(date1 + " - " + date2)
    #if int(date2[6:8])-int(date1[6:8]) >0:
    #    return ("<div style='font-size:xxx-large'>Reduce Timespan to 24 hours</div>")
    in_year=f"{date1[0:4]}"
    in_month=f"{date1[4:6]}"
    in_day=f"{date1[6:8]}"
    
    end_year=f"{date2[0:4]}"
    end_month=f"{date2[4:6]}"
    end_day=f"{date2[6:8]}"
    
    sdo_urls = generate_sdo_urls(date1,date2)
    print(sdo_urls)
    
    '''years_rem,months_rem,days_rem=(0,0,0)
    og_days_rem=days_rem
    i_in_year,i_in_month,i_in_day,i_end_year,i_end_month,i_end_day=int(in_year),int(in_month),int(in_day),int(end_year),int(end_month),int(end_day)
    days_json={"year": 0, "month": 0, "day": 0}
    if i_end_year > i_in_year:
        years_rem = i_end_year-i_in_year
    if i_end_month > i_in_month:
        months_rem = 12 - i_in_month
    if i_end_day > i_in_day:
        og_days_rem = month_dict[in_month] - i_in_day
        
    if years_rem > 0:
        for ii in list(range(0,years_raw)):
            months_rem+=years_rem*12
            out_year = in_year+ii
            for i in list(range(0,months_rem)):
                month_day_cnt = month_dict[str(int(in_month)+i)]
                for io in list(range(0,month_day_cnt)):
                    days_rem += month_day_cnt
                    out_url=f"https://sdo.gsfc.nasa.gov/assets/img/browse/{out_year}/{i}/{io}/"
                    print(out_url)
                    url_box.append(out_url)
        months_raw = 0
    if months_rem > 0:
        out_year = in_year
        for i in list(range(0,months_rem)):
            month_day_cnt = month_dict[str(int(in_month)+i)]
            for io in list(range(0,month_day_cnt)):
                days_rem += month_day_cnt
                out_url=f"https://sdo.gsfc.nasa.gov/assets/img/browse/{out_year}/{i}/{io}/"
                print(out_url)
                url_box.append(out_url)
        og_days_rem=0
    if og_days_rem > 0:
        for io in list(range(0,og_days_rem)):
            days_rem += io
            out_url=f"https://sdo.gsfc.nasa.gov/assets/img/browse/{end_year}/{end_month}/{io}/"
            print(out_url)
            url_box.append(out_url)'''
    
    file_name="DATE_TIME_SIZE_TOOL.jpg"
    out_box=[]
    sdo_urls.sort(reverse=True)
    for num, link in enumerate(sdo_urls):
        link_box=[]
        print(link)
        #sdo_source_format = f"https://sdo.gsfc.nasa.gov/assets/img/browse/{in_year}/{in_month}/{in_day}/"
        sdo_source_format = link
        #get_url=sdo_source_format
        feed1 = requests.get(link)    
        #print(get_url)
        if "All" in size:
            size = sdo_size
        if "All" in obj:
            obj = sdo_obj
        # Parse the HTML content using BeautifulSoup
        soup = bs4.BeautifulSoup(feed1.content, 'html.parser')
        #print(soup)
        anchor_elements = soup.find_all('a')
        for element in anchor_elements:
            link_box.append(element.get('href'))
            
        link_box.sort(reverse=True)
        #for element in anchor_elements:
        for href in link_box:
            #print(href)
            #href=element.get('href')
            if href.endswith('.jpg'):
                for o in obj:
                    for s in size:
                        ls=href.split("_")
                        #print(ls[1][0:4])
                        #print(date1[8:13])
                        if ls[1][0:4]>=date1[8:13]:
                            src_obj=ls[3].split('.jpg')[0]
                            if src_obj == o:
                                if int(ls[2]) == int(s):
                                    print(f"{link}{href}")
                                    out_box.append(f'{link}{href}')
                                    html_in+=f'<div class="img_class_sdo"><a href="{link}{href}" target="_blank">{href}</a><br><img src={link}{href}></div>'
                        else:
                            src_obj=ls[3].split('.jpg')[0]
                            if src_obj == o:
                                if int(ls[2]) == int(s):
                                    print(f"{link}{href}")
                                    out_box.append(f'{link}{href}')
                                    html_in+=f'<div class="img_class_sdo"><a href="{link}{href}" target="_blank">{href}</a><br><img src={link}{href}></div>'


    return html_in, out_box

def get_concat_h_cut(in1, in2):
    uid=uuid.uuid4()
    im1=Image.open(in1)
    im2=Image.open(in2)
    dst = Image.new('RGB', (im1.width + im2.width,
                            min(im1.height, im2.height)))
    dst.paste(im1, (0, 0))
    dst.paste(im2, (im1.width, 0))
    dst.save(f"h_{uid}.jpg")
    return f"h_{uid}.jpg"


def get_concat_v_cut(in1, in2, theme='dark'):
    uid=uuid.uuid4()
    im1=Image.open(in1)
    im2=Image.open(in2)
    if theme=='dark':
        color=(31,41,55)
    if theme=='light':
        color=(255,255,255)
    dst = Image.new('RGB', (min(im1.width, im2.width), im1.height + im2.height),color=color)
    dst.paste(im1, (0, 0))
    dst.paste(im2, (0, im1.height))
    dst.save(f"v_{uid}.jpg")
    return f"v_{uid}.jpg"




def nasa_sdo_composite(obj,size,date1,date2,ret_num):
    html_in=f"<style>{css}</style><div class='img_box_soho'>"
    #if int(date2[6:8])-int(date1[6:8]) >0:
    #    return ("<div style='font-size:xxx-large'>Reduce Timespan to 24 hours</div>")
    in_year=f"{date2[0:4]}"
    in_month=f"{date2[4:6]}"
    in_day=f"{date2[6:8]}"
    file_name="DATE_TIME_SIZE_TOOL.jpg"
    sdo_source_format = f"https://sdo.gsfc.nasa.gov/assets/img/browse/{in_year}/{in_month}/{in_day}/"
    get_url=sdo_source_format
    print(get_url)
    feed1 = requests.get(get_url)    
    if "All" in size:
        size = sdo_size
    if "All" in obj:
        obj = sdo_obj
    link_box=[]
    soup = bs4.BeautifulSoup(feed1.content, 'html.parser')
    anchor_elements = soup.find_all('a')
    #anchor_elements.sort()
    cnt=1
    max_cnt=ret_num
    for element in anchor_elements:
        href=element.get('href')
        if href.endswith('.jpg'):
            for o in obj:
                for s in size:
                    ls=href.split("_")
                    #print(ls[1][0:4])
                    #print(date1[8:13])
                    if ls[1][0:4]>=date1[8:13]:
                        src_obj=ls[3].split('.jpg')[0]
                        if src_obj == o:
                            if int(ls[2]) == int(s):
                                link_box.append(href)
                    

    #print(link_box)
    #print("$$$$$$$$$$$$$$$$$")
    link_box.sort(reverse=True)
    #print(link_box)
    out_box=[]
    for ea in link_box:
        if cnt<=max_cnt:
            out_link=f'{sdo_source_format}{ea}'
            out_box.append(out_link)
            cnt+=1
            html_in+=f'<div class="img_class_sdo"><a href="{sdo_source_format}{ea}" target="_blank">{ea}</a><br><img src={sdo_source_format}{ea}></div>'
        
    html_in+="</div>"
    return html_in, out_box
            
def run():
    out=make_tree()
    im_html=get_images()
    return im_html
def get_date(year1,month1,day1,hour1,minute1,year2,month2,day2,hour2,minute2):
    if len(str(month1))<2: m1=0
    else: m1=""
    if len(str(day1))<2: d1=0
    else: d1=""
    if len(str(hour1))<2: h1=0
    else: h1=""
    if len(str(minute1))<2: mi1=0
    else: mi1=""
    date1=f'{year1}{m1}{month1}{d1}{day1}{h1}{hour1}{mi1}{minute1}'

    if len(str(month2))<2: m2=0
    else: m2=""
    if len(str(day2))<2: d2=0
    else: d2=""
    if len(str(hour2))<2: h2=0
    else: h2=""
    if len(str(minute2))<2: mi2=0
    else: mi2=""
    date2=f'{year2}{m2}{month2}{d2}{day2}{h2}{hour2}{mi2}{minute2}'
    print(date1)
    print(date2)
    return date1,date2
def comp_combine(inp_ims: list,comp_col,comp_row,resize=False):
    #print(inp_ims)
    im_box=[]
    v_box=[]
    rows=comp_row
    cols=comp_col
    if not type(inp_ims)==type([]):
        inp_ims=eval(inp_ims)
    for i,im in enumerate(inp_ims):
        urllib.request.urlretrieve(im, f"tmp-{i}.jpg")
        if resize:
            pil_im = Image.open(f'tmp-{i}.jpg')
            pil_im = pil_im.resize((int(resize[0]),int(resize[1])),resample=Image.Resampling.LANCZOS).convert('RGB')
            pil_im.save(f'tmp-{i}.jpg')
        im_box.append(f"tmp-{i}.jpg")
    im_cnt=len(im_box)
    cnt=1
    for rr in range(rows):
    
        print(rr)
        col_start=[im_box[cnt-1]]
        for cc in range(cols-1):
            try:
                print(cc)
                col_out=get_concat_h_cut(col_start[0],im_box[cnt])
                col_start[0]=col_out
                cnt+=1
                #if cnt>=im_cnt:
                #    rr=range(rows)
                #    cc=range(cols)
            except Exception as e:
                print(e)
                pass                
        cnt+=1
        v_box.append(col_out)

    print(v_box)
    v_cnt=1
    v_box_cnt=len(v_box)
    v_start=[v_box[0]]
    for vv in range(v_box_cnt-1):
        print(vv)
        v_out=get_concat_v_cut(v_start[0],v_box[v_cnt])
        v_start[0]=v_out
        v_cnt+=1
    return v_out
def comp_1(comp_list=comp_list,col=3,row=4,resize=[640,450]):
    #1280x900
    outp=comp_combine(comp_list,col,row,resize)
    return (outp)
datestamp=["1","1","1"]
timestamp=["1","1","1"]
datetimestamp="1:1:1"
def get_time():
    datetimestamp=str(datetime.datetime.now()).split(".")[0]
    datestamp=datetimestamp.replace(" ","-").split("-")
    timestamp=datestamp[3].split(":")

    html_out=f"""<div style='font-size:xxx-large;'>Current: {datetimestamp} UTC</div>"""
    year1=int(datestamp[0])
    month1=int(datestamp[1])
    day1=int(datestamp[2])
    hour1=int(timestamp[0])
    minute1=int(timestamp[1])
    year2=int(datestamp[0])
    month2=int(datestamp[1])
    day2=int(datestamp[2])
    hour2=int(timestamp[0])
    minute2=int(timestamp[1])
    return (gr.update(value=html_out),gr.update(value=year1),gr.update(value=month1),
    gr.update(value=day1),gr.update(value=hour1),gr.update(value=minute1),
    gr.update(value=year2),gr.update(value=month2),gr.update(value=day2),gr.update(value=hour2),gr.update(value=minute2))
    
with gr.Blocks() as app:
    #datetimestamp=gr.Textbox()
    #datestamp=gr.Textbox()
    url_list=gr.State([])
    datetimestamp=str(datetime.datetime.now()).split(".")[0]
    datestamp=datetimestamp.replace(" ","-").split("-")
    timestamp=datestamp[3].split(":")
    
    time_html=gr.HTML(f"""<div style='font-size:xxx-large;'>Current: {datetimestamp} UTC</div>""")
    with gr.Tab("NOAA"):
        with gr.Tab("Compilation"):
            first_comp_btn=gr.Button("Load")
            first_comp_img=gr.Image()
        with gr.Tab("Images"):
            first_btn=gr.Button("Load")
            html_im=gr.HTML()
        with gr.Tab("Animations"):
            anim_btn=gr.Button()
            anim_out=gr.HTML() 
            file_out=gr.Files()
        with gr.Tab("Raw"):
            with gr.Row():
                drop1=gr.Dropdown()
                drop2=gr.Dropdown()
                drop3=gr.Dropdown()
                drop4=gr.Dropdown()
            with gr.Row():
                drop5=gr.Dropdown()
                drop6=gr.Dropdown()
                drop7=gr.Dropdown()
                drop8=gr.Dropdown()
            load_btn=gr.Button("Load")
            html_raw=gr.HTML()
            links=gr.JSON()
    with gr.Tab("NASA"):
        with gr.Tab("SDO Images"):
            with gr.Row():
                gr.Markdown("<h5 style='font-size:xx-large;'>From:")
                year1=gr.Number(label="Year",minimum=2000,maximum=2025,precision=0,value=int(datestamp[0]),min_width=10)
                month1=gr.Number(label="Month",minimum=1,maximum=12,precision=0,value=int(datestamp[1]),min_width=10)
                day1=gr.Number(label="Day",minimum=1,maximum=31,precision=0,value=int(datestamp[2]),min_width=10)
                hour1=gr.Number(label="Hour",minimum=0,maximum=23,precision=0,value=int(timestamp[0]),min_width=10)
                minute1=gr.Number(label="Minute",minimum=0,maximum=59,precision=0,value=int(timestamp[1]),min_width=10)
                gr.Markdown("<h5 style='font-size:xx-large;'>To:")
                year2=gr.Number(label="Year",minimum=2000,maximum=2025,precision=0,value=int(datestamp[0]),min_width=10)
                month2=gr.Number(label="Month",minimum=1,maximum=12,precision=0,value=int(datestamp[1]),min_width=10)
                day2=gr.Number(label="Day",minimum=1,maximum=31,precision=0,value=int(datestamp[2]),min_width=10)
                hour2=gr.Number(label="Hour",minimum=0,maximum=23,precision=0,value=int(timestamp[0]),min_width=10)
                minute2=gr.Number(label="Minute",minimum=0,maximum=59,precision=0,value=int(timestamp[1]),min_width=10)
                
            with gr.Row():
                sdo_drop1=gr.Dropdown(label="Instrument", multiselect=True, choices=["All"]+sdo_obj, value="0094")
                sdo_drop2=gr.Dropdown(label="Size", multiselect=True, choices=["All"]+sdo_size,value=512)
            
            with gr.Tab("Composite"):
                with gr.Row():
                    comp_num=gr.Number(label="Return",precision=0,value=4,interactive=True)
                    comp_col=gr.Number(label="Columns",precision=0,value=2,interactive=True)
                    comp_row=gr.Number(label="Rows",precision=0,value=2,interactive=True)
                with gr.Row():
                    comp_combine_btn=gr.Button("Combine")
                    sdo_comp_btn=gr.Button("Load")
                img_out=gr.Image()
                comp_combine_html=gr.HTML()                
                sdo_comp_html=gr.HTML()
                image_comp_list=gr.Textbox(visible=True)
            with gr.Tab("Images"):
                sdo_btn=gr.Button("Load")
                sdo_gif=gr.Button("Make GIF")
                sdo_gif_html=gr.HTML()
                sdo_gif.click(make_animation_new,url_list,sdo_gif_html)
                sdo_html=gr.HTML()
        
                
            date1=gr.Textbox(visible=False)
            date2=gr.Textbox(visible=False)
            #sdo_json=gr.JSON()
        with gr.Tab("SOHO Images"):
            soho_btn=gr.Button("Load")
            html_nasa=gr.HTML()
        with gr.Tab("SOHO Video"):
            soho_vid_btn=gr.Button("Load")
            html_vid_nasa=gr.HTML()
    app.load(get_time,None,[time_html,year1,month1,day1,hour1,minute1,year2,month2,day2,hour2,minute2]).then(make_tree,None,drop1)

    first_comp_btn.click(comp_1,None,first_comp_img)
    ###### Composite Images ##########
    comp_combine_btn.click(comp_combine,[image_comp_list,comp_col,comp_row],img_out)
    sdo_comp_btn.click(get_date,[year1,month1,day1,hour1,minute1,year2,month2,day2,hour2,minute2],[date1,date2]).then(nasa_sdo_composite,[sdo_drop1,sdo_drop2,date1,date2,comp_num],[sdo_comp_html,image_comp_list])

    ###### NASA Images ##########
    sdo_btn.click(get_date,[year1,month1,day1,hour1,minute1,year2,month2,day2,hour2,minute2],[date1,date2]).then(nasa_sdo_images,[sdo_drop1,sdo_drop2,date1,date2],[sdo_html,url_list])
    soho_btn.click(make_nasa_soho_image_trigger,None,html_nasa)
    soho_vid_btn.click(make_nasa_soho_videos,None,html_vid_nasa)
    ###### NOAA Images ##########
    load_btn.click(load_json,[drop1,drop2,drop3,drop4,drop5,drop6,drop7,drop8],[html_raw,links])
    anim_btn.click(make_animation,None,[file_out]).then(make_html,file_out,anim_out)
    ####### Raw ############
    drop1.change(make_tree,drop1,[drop2])
    drop2.change(make_tree,[drop1,drop2],[drop3])
    drop3.change(make_tree,[drop1,drop2,drop3],[drop4])
    drop4.change(make_tree,[drop1,drop2,drop3,drop4],[drop5])
    drop5.change(make_tree,[drop1,drop2,drop3,drop4,drop5],[drop6])
    drop6.change(make_tree,[drop1,drop2,drop3,drop4,drop5,drop6],[drop7])
    drop7.change(make_tree,[drop1,drop2,drop3,drop4,drop5,drop6,drop7],[drop8])

    
    ######################
    first_btn.click(run,None,[html_im])
    #app.load(make_tree,None,drop1)
app.queue(default_concurrency_limit=10).launch()