Spaces:
Sleeping
Sleeping
File size: 52,280 Bytes
70e5fcc 54016d6 |
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 |
#!/usr/bin/env python3
"""
NASA Solar Image Downloader - Hugging Face Spaces Version
Complete web interface with all features from the original application.
"""
import os
import sys
import io
import base64
from pathlib import Path
from datetime import datetime, timedelta
import subprocess
import shutil
import threading
import time
import tempfile
try:
import gradio as gr
from PIL import Image
import requests
from bs4 import BeautifulSoup
import numpy as np
except ImportError as e:
print(f"โ Required libraries not available: {e}")
print("๐ก Install with: pip install gradio pillow requests beautifulsoup4")
sys.exit(1)
class NASADownloaderHF:
"""Complete NASA Solar Image Downloader for Hugging Face Spaces."""
def __init__(self):
"""Initialize the application."""
self.resolution = "1024"
self.solar_filter = "0211"
# Create temporary directories
self.temp_dir = Path(tempfile.mkdtemp())
self.data_dir = self.temp_dir / "data"
self.video_dir = self.temp_dir / "video"
self.data_dir.mkdir(exist_ok=True)
self.video_dir.mkdir(exist_ok=True)
# Filter data with full information and thumbnail paths
self.filter_data = {
"0193": {"name": "193 ร
", "desc": "Coronal loops", "color": "#ff6b6b", "image": "src/ui_img/20251220_000753_1024_0193.jpg"},
"0304": {"name": "304 ร
", "desc": "Chromosphere", "color": "#4ecdc4", "image": "src/ui_img/20251220_000854_1024_0304.jpg"},
"0171": {"name": "171 ร
", "desc": "Quiet corona", "color": "#45b7d1", "image": "src/ui_img/20251220_000658_1024_0171.jpg"},
"0211": {"name": "211 ร
", "desc": "Active regions", "color": "#f9ca24", "image": "src/ui_img/20251220_000035_1024_0211.jpg"},
"0131": {"name": "131 ร
", "desc": "Flaring regions", "color": "#f0932b", "image": "src/ui_img/20251220_000644_1024_0131.jpg"},
"0335": {"name": "335 ร
", "desc": "Active cores", "color": "#eb4d4b", "image": "src/ui_img/20251220_000114_1024_0335.jpg"},
"0094": {"name": "94 ร
", "desc": "Hot plasma", "color": "#6c5ce7", "image": "src/ui_img/20251220_000600_1024_0094.jpg"},
"1600": {"name": "1600 ร
", "desc": "Transition region", "color": "#a29bfe", "image": "src/ui_img/20251220_000151_1024_1600.jpg"},
"1700": {"name": "1700 ร
", "desc": "Temperature min", "color": "#fd79a8", "image": "src/ui_img/20251220_000317_1024_1700.jpg"},
"094335193": {"name": "094+335+193", "desc": "Composite: Hot plasma + Active cores + Coronal loops", "color": "#8e44ad", "image": "src/ui_img/20251219_000311_1024_094335193.jpg"},
"304211171": {"name": "304+211+171", "desc": "Composite: Chromosphere + Active regions + Quiet corona", "color": "#e67e22", "image": "src/ui_img/20251219_000311_1024_304211171.jpg"},
"211193171": {"name": "211+193+171", "desc": "Composite: Active regions + Coronal loops + Quiet corona", "color": "#27ae60", "image": "src/ui_img/20251219_001633_1024_211193171.jpg"}
}
# Custom keywords for advanced users
self.custom_keywords = {filter_num: filter_num for filter_num in self.filter_data.keys()}
# Image viewer state
self.current_images = []
self.current_image_index = 0
self.is_playing = False
self.play_speed = 120.0 # FPS for playback
self.last_update_time = 0 # Track last update time for playback
def get_filter_gallery_data(self):
"""Get gallery data for filter selection with thumbnails."""
gallery_data = []
for filter_key, data in self.filter_data.items():
# Create gallery item with image path and caption
caption = f"{data['name']}\n{data['desc']}"
gallery_data.append((data['image'], caption))
return gallery_data
def get_filter_key_from_gallery_index(self, index):
"""Get filter key from gallery selection index."""
filter_keys = list(self.filter_data.keys())
if 0 <= index < len(filter_keys):
return filter_keys[index]
return "0211" # Default
def on_filter_gallery_select(self, evt: gr.SelectData):
"""Handle filter gallery selection."""
if evt.index is not None:
filter_key = self.get_filter_key_from_gallery_index(evt.index)
filter_data = self.filter_data[filter_key]
info_text = f"**Selected:** {filter_data['name']} - {filter_data['desc']}"
return filter_key, info_text
return "0211", "**Selected:** 211 ร
- Active regions"
def set_date_range(self, days_back):
"""Set date range for quick selection."""
end_date = datetime.now()
start_date = end_date - timedelta(days=days_back)
return start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d")
def get_nasa_image_url(self, date, resolution, solar_filter):
"""Generate NASA SDO image URL."""
base_url = "https://sdo.gsfc.nasa.gov/assets/img/browse"
year = date.strftime("%Y")
month = date.strftime("%m")
day = date.strftime("%d")
# Try different time stamps (NASA updates throughout the day)
for hour in ["23", "22", "21", "20", "19", "18", "12", "06", "00"]:
for minute in ["59", "30", "00"]:
for second in ["59", "30", "00"]:
timestamp = f"{hour}{minute}{second}"
filename = f"{date.strftime('%Y%m%d')}_{timestamp}_{resolution}_{solar_filter}.jpg"
url = f"{base_url}/{year}/{month}/{day}/{filename}"
# Check if URL exists
try:
response = requests.head(url, timeout=5)
if response.status_code == 200:
return url, filename
except:
continue
return None, None
def download_images(self, start_date, end_date, resolution, solar_filter, progress=gr.Progress()):
"""Download images for the specified date range."""
try:
# Update settings
self.resolution = resolution
self.solar_filter = solar_filter
# Use custom keyword if available
search_keyword = self.custom_keywords.get(solar_filter, solar_filter)
# Parse dates
start = datetime.strptime(start_date, "%Y-%m-%d")
end = datetime.strptime(end_date, "%Y-%m-%d")
# Limit to maximum 7 days for HF Spaces
if (end - start).days > 7:
return "โ Please limit date range to 7 days maximum for cloud deployment.", self.get_available_dates()
progress(0, desc="Starting download...")
downloaded = 0
failed = 0
current_date = start
total_days = (end - start).days + 1
while current_date <= end:
progress(downloaded / total_days, desc=f"Downloading {current_date.strftime('%Y-%m-%d')}")
url, filename = self.get_nasa_image_url(current_date, resolution, search_keyword)
if url:
try:
# Download the image
response = requests.get(url, timeout=30)
if response.status_code == 200:
# Save to temporary directory
date_dir = self.data_dir / current_date.strftime("%Y") / current_date.strftime("%m") / current_date.strftime("%d")
date_dir.mkdir(parents=True, exist_ok=True)
image_path = date_dir / filename
with open(image_path, 'wb') as f:
f.write(response.content)
downloaded += 1
else:
failed += 1
except:
failed += 1
else:
failed += 1
current_date += timedelta(days=1)
progress(1.0, desc="Complete!")
result = f"โ
Download complete!\n"
result += f"๐ฅ Downloaded: {downloaded} images\n"
result += f"โ Failed: {failed} images\n"
result += f"๐ Filter: {self.filter_data[solar_filter]['name']} - {self.filter_data[solar_filter]['desc']}"
return result, self.get_available_dates()
except Exception as e:
return f"โ Error: {str(e)}", self.get_available_dates()
def get_available_dates(self, resolution=None, solar_filter=None):
"""Get list of available dates with images for specific resolution and filter."""
dates = []
if self.data_dir.exists():
for year_dir in self.data_dir.iterdir():
if not year_dir.is_dir() or not year_dir.name.isdigit():
continue
for month_dir in year_dir.iterdir():
if not month_dir.is_dir() or not month_dir.name.isdigit():
continue
for day_dir in month_dir.iterdir():
if not day_dir.is_dir() or not day_dir.name.isdigit():
continue
# Count images in this directory
images = list(day_dir.glob("*.jpg"))
if images:
try:
date = datetime(int(year_dir.name), int(month_dir.name), int(day_dir.name))
date_str = f"{date.strftime('%Y-%m-%d')} ({len(images)} images)"
dates.append(date_str)
except ValueError:
continue
return sorted(dates, reverse=True)
def load_images_for_date_range(self, from_date, to_date, resolution, solar_filter):
"""Load images for a date range with specific resolution and filter."""
try:
# Update settings
self.resolution = resolution
self.solar_filter = solar_filter
start_date = datetime.strptime(from_date.split(' ')[0], "%Y-%m-%d")
end_date = datetime.strptime(to_date.split(' ')[0], "%Y-%m-%d")
# Ensure from_date is not after to_date
if start_date > end_date:
start_date, end_date = end_date, start_date
# Load images from all dates in the range
self.current_images = []
total_images = 0
# Get all dates in range
current_date = start_date
while current_date <= end_date:
date_dir = self.data_dir / current_date.strftime("%Y") / current_date.strftime("%m") / current_date.strftime("%d")
if date_dir.exists():
images = list(date_dir.glob("*.jpg"))
for image_path in sorted(images):
self.current_images.append((str(image_path), image_path.name, current_date))
total_images += 1
current_date += timedelta(days=1)
if not self.current_images:
filter_name = self.filter_data[solar_filter]['name']
return None, f"โ No images found for date range {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}\nResolution: {resolution}px, Filter: {filter_name}", "0 / 0"
# Sort all images by filename (which includes timestamp)
self.current_images.sort(key=lambda x: x[1])
self.current_image_index = 0
date_range_text = f"{start_date.strftime('%Y-%m-%d')}" if start_date == end_date else f"{start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}"
filter_name = self.filter_data[solar_filter]['name']
return self.current_images[0][0], f"โ
Loaded {total_images} images for {date_range_text}\nResolution: {resolution}px, Filter: {filter_name}", f"1 / {len(self.current_images)}"
except Exception as e:
return None, f"โ Error: {str(e)}", "0 / 0"
def navigate_image(self, direction):
"""Navigate through images."""
if not self.current_images:
return None, "No images loaded", "0 / 0", "โถ Play"
if direction == "first":
self.current_image_index = 0
elif direction == "prev":
self.current_image_index = max(0, self.current_image_index - 1)
elif direction == "next":
self.current_image_index = min(len(self.current_images) - 1, self.current_image_index + 1)
elif direction == "last":
self.current_image_index = len(self.current_images) - 1
current_image = self.current_images[self.current_image_index]
image_path, filename, image_date = current_image
# Extract timestamp
timestamp = filename.split('_')[1] if '_' in filename else "Unknown"
if len(timestamp) == 6:
formatted_time = f"{timestamp[:2]}:{timestamp[2:4]}:{timestamp[4:6]}"
else:
formatted_time = timestamp
info_text = f"๐
{image_date.strftime('%Y-%m-%d')} โฐ {formatted_time}"
position_text = f"{self.current_image_index + 1} / {len(self.current_images)}"
play_button_text = "โธ Pause" if self.is_playing else "โถ Play"
return image_path, info_text, position_text, play_button_text
def toggle_play(self):
"""Toggle play/pause for image sequence."""
if not self.current_images:
return None, "No images loaded", "0 / 0", "โถ Play", f"{self.play_speed:.1f} FPS"
if self.is_playing:
self.is_playing = False
play_button_text = "โถ Play"
else:
self.is_playing = True
play_button_text = "โธ Pause"
self.last_update_time = time.time() # Reset timer
current_image = self.current_images[self.current_image_index]
image_path, filename, image_date = current_image
# Extract timestamp
timestamp = filename.split('_')[1] if '_' in filename else "Unknown"
if len(timestamp) == 6:
formatted_time = f"{timestamp[:2]}:{timestamp[2:4]}:{timestamp[4:6]}"
else:
formatted_time = timestamp
info_text = f"๐
{image_date.strftime('%Y-%m-%d')} โฐ {formatted_time}"
position_text = f"{self.current_image_index + 1} / {len(self.current_images)}"
return image_path, info_text, position_text, play_button_text, f"{self.play_speed:.1f} FPS"
def update_playback(self):
"""Update playback - called by timer."""
if not self.is_playing or not self.current_images:
# Return current state without changes
if not self.current_images:
return None, "No images loaded", "0 / 0", "โถ Play", f"{self.play_speed:.1f} FPS"
current_image = self.current_images[self.current_image_index]
image_path, filename, image_date = current_image
# Extract timestamp
timestamp = filename.split('_')[1] if '_' in filename else "Unknown"
if len(timestamp) == 6:
formatted_time = f"{timestamp[:2]}:{timestamp[2:4]}:{timestamp[4:6]}"
else:
formatted_time = timestamp
info_text = f"๐
{image_date.strftime('%Y-%m-%d')} โฐ {formatted_time}"
position_text = f"{self.current_image_index + 1} / {len(self.current_images)}"
play_button_text = "โธ Pause" if self.is_playing else "โถ Play"
return image_path, info_text, position_text, play_button_text, f"{self.play_speed:.1f} FPS"
# Check if enough time has passed for next frame
current_time = time.time()
frame_interval = 1.0 / self.play_speed
if current_time - self.last_update_time >= frame_interval:
# Advance to next image
if self.current_image_index >= len(self.current_images) - 1:
self.current_image_index = 0 # Loop back to start
else:
self.current_image_index += 1
self.last_update_time = current_time
# Return current image
current_image = self.current_images[self.current_image_index]
image_path, filename, image_date = current_image
# Extract timestamp
timestamp = filename.split('_')[1] if '_' in filename else "Unknown"
if len(timestamp) == 6:
formatted_time = f"{timestamp[:2]}:{timestamp[2:4]}:{timestamp[4:6]}"
else:
formatted_time = timestamp
info_text = f"๐
{image_date.strftime('%Y-%m-%d')} โฐ {formatted_time}"
position_text = f"{self.current_image_index + 1} / {len(self.current_images)}"
play_button_text = "โธ Pause"
return image_path, info_text, position_text, play_button_text, f"{self.play_speed:.1f} FPS"
def update_play_speed(self, speed):
"""Update playback speed."""
self.play_speed = float(speed)
return f"{self.play_speed:.1f} FPS"
def create_video(self, start_date, end_date, fps, resolution, solar_filter, progress=gr.Progress()):
"""Create MP4 video from images."""
try:
# Update settings
self.resolution = resolution
self.solar_filter = solar_filter
# Parse dates
start = datetime.strptime(start_date, "%Y-%m-%d")
end = datetime.strptime(end_date, "%Y-%m-%d")
progress(0.1, desc="Collecting images...")
# Collect all images from the date range
all_image_paths = []
current_date = start
while current_date <= end:
date_dir = self.data_dir / current_date.strftime("%Y") / current_date.strftime("%m") / current_date.strftime("%d")
if date_dir.exists():
images = list(date_dir.glob("*.jpg"))
for image_path in sorted(images):
if image_path.exists():
all_image_paths.append(image_path)
current_date += timedelta(days=1)
if not all_image_paths:
return None, f"โ No images found for date range {start_date} to {end_date}"
progress(0.2, desc=f"Found {len(all_image_paths)} images. Creating video...")
# Generate output filename
if start == end:
output_file = f"nasa_solar_{start.strftime('%Y%m%d')}.mp4"
else:
output_file = f"nasa_solar_{start.strftime('%Y%m%d')}_to_{end.strftime('%Y%m%d')}.mp4"
output_path = self.video_dir / output_file
# Note: FFmpeg may not be available in HF Spaces
# This is a placeholder - video creation may not work in cloud environment
progress(1.0, desc="Video creation not available in cloud environment")
message = f"โ ๏ธ Video creation requires FFmpeg which may not be available in cloud environment.\n"
message += f"๐ Would create: {output_file}\n"
message += f"๐๏ธ Frames: {len(all_image_paths)}\n"
message += f"๐ Filter: {self.filter_data[solar_filter]['name']}"
return None, message
except Exception as e:
return None, f"โ Error: {str(e)}"
def get_video_list(self):
"""Get list of available video files."""
if not self.video_dir.exists():
return []
videos = []
for video_file in self.video_dir.glob("*.mp4"):
try:
size_mb = video_file.stat().st_size / (1024 * 1024)
videos.append(f"{video_file.name} ({size_mb:.1f} MB)")
except:
videos.append(video_file.name)
return sorted(videos, reverse=True)
def open_data_folder(self):
"""Open data folder (returns path for web interface)."""
return f"๐ Data folder location: {self.data_dir.absolute()}"
def cleanup_corrupted_files(self):
"""Clean up corrupted files."""
total_removed = 0
if self.data_dir.exists():
for year_dir in self.data_dir.iterdir():
if not year_dir.is_dir():
continue
for month_dir in year_dir.iterdir():
if not month_dir.is_dir():
continue
for day_dir in month_dir.iterdir():
if not day_dir.is_dir():
continue
# Check for corrupted files (very basic check)
for image_file in day_dir.glob("*.jpg"):
try:
if image_file.stat().st_size < 1000: # Less than 1KB
image_file.unlink()
total_removed += 1
except:
continue
return f"๐งน Cleanup complete! Removed {total_removed} corrupted files."
def get_system_info(self):
"""Get system information."""
info = "๐ฅ๏ธ **System Information**\n\n"
# Check FFmpeg
try:
result = subprocess.run(['ffmpeg', '-version'], capture_output=True, timeout=5)
ffmpeg_status = "โ
Available" if result.returncode == 0 else "โ Not found"
except:
ffmpeg_status = "โ Not found (Cloud Environment)"
info += f"**FFmpeg**: {ffmpeg_status}\n"
# Check PIL
try:
from PIL import Image
pil_status = f"โ
Available"
except:
pil_status = "โ Not found"
info += f"**Pillow**: {pil_status}\n\n"
# Data directory info
if self.data_dir.exists():
info += f"**Data Directory**: {self.data_dir.absolute()}\n"
# Count total images
total_images = 0
for image_file in self.data_dir.rglob("*.jpg"):
total_images += 1
info += f"**Total Images**: {total_images}\n"
else:
info += f"**Data Directory**: Not created yet\n"
info += f"\n**Environment**: Hugging Face Spaces\n"
info += f"**Created by Andy Kong**"
return info
def update_custom_keyword(self, filter_name, keyword):
"""Update custom keyword for a filter."""
if filter_name in self.custom_keywords:
self.custom_keywords[filter_name] = keyword.strip() if keyword.strip() else filter_name
return f"โ
Updated {filter_name} keyword to: {self.custom_keywords[filter_name]}"
return f"โ Invalid filter: {filter_name}"
def reset_custom_keywords(self):
"""Reset all custom keywords to defaults."""
self.custom_keywords = {filter_num: filter_num for filter_num in self.filter_data.keys()}
return "โ
All keywords reset to defaults"
def create_interface(self):
"""Create the complete Gradio interface with all features."""
with gr.Blocks(title="๐ NASA Solar Image Downloader") as app:
gr.Markdown("# ๐ NASA Solar Image Downloader")
gr.Markdown("**Complete web interface** - Download, view, and create videos from NASA Solar Dynamics Observatory images")
gr.Markdown("โ ๏ธ **Cloud Version**: Limited to 7 days maximum per download. Video creation may not be available.")
with gr.Tabs():
# Download Tab
with gr.Tab("๐ฅ Download Images"):
gr.Markdown("### Download NASA Solar Images")
with gr.Row():
with gr.Column():
gr.Markdown("#### ๐๏ธ Quick Date Selection")
with gr.Row():
today_btn = gr.Button("Today", size="sm")
last3_btn = gr.Button("Last 3 Days", size="sm")
lastweek_btn = gr.Button("Last Week", size="sm")
gr.Markdown("#### ๐
Custom Date Range")
download_start_date = gr.Textbox(
label="Start Date (YYYY-MM-DD)",
value=datetime.now().strftime("%Y-%m-%d")
)
download_end_date = gr.Textbox(
label="End Date (YYYY-MM-DD)",
value=datetime.now().strftime("%Y-%m-%d")
)
gr.Markdown("#### ๐ง Image Settings")
download_resolution = gr.Dropdown(
choices=["1024", "2048", "4096"],
value="1024",
label="Resolution (pixels)"
)
download_btn = gr.Button("๐ Find & Download Images", variant="primary", size="lg")
with gr.Column():
gr.Markdown("#### ๐ Solar Filter Selection")
gr.Markdown("*Click on a thumbnail to select a solar filter*")
download_filter_gallery = gr.Gallery(
value=self.get_filter_gallery_data(),
label="Solar Filters",
columns=4,
rows=3,
height="auto",
object_fit="contain",
show_label=False,
selected_index=3 # Default to 0211
)
# Hidden state to store the selected filter key
download_filter = gr.State(value="0211")
# Display selected filter info
download_filter_info = gr.Markdown("**Selected:** 211 ร
- Active regions")
download_output = gr.Textbox(label="Download Status", lines=8)
# Quick date button actions
today_btn.click(
fn=lambda: self.set_date_range(0),
outputs=[download_start_date, download_end_date]
)
last3_btn.click(
fn=lambda: self.set_date_range(2),
outputs=[download_start_date, download_end_date]
)
lastweek_btn.click(
fn=lambda: self.set_date_range(6),
outputs=[download_start_date, download_end_date]
)
# Store available dates for refresh
available_dates_state = gr.State(value=self.get_available_dates())
# Gallery selection event for download tab
download_filter_gallery.select(
fn=self.on_filter_gallery_select,
outputs=[download_filter, download_filter_info]
)
download_btn.click(
fn=self.download_images,
inputs=[download_start_date, download_end_date, download_resolution, download_filter],
outputs=[download_output, available_dates_state]
)
# View Images Tab
with gr.Tab("๐๏ธ View Images"):
gr.Markdown("### View Downloaded Images with Full Playback Controls")
with gr.Row():
with gr.Column():
gr.Markdown("#### ๐ง Image Settings")
with gr.Row():
view_resolution = gr.Dropdown(
choices=["1024", "2048", "4096"],
value="1024",
label="Resolution (pixels)",
scale=1
)
gr.Markdown("#### ๐ Solar Filter Selection")
gr.Markdown("*Click on a thumbnail to select a solar filter*")
view_filter_gallery = gr.Gallery(
value=self.get_filter_gallery_data(),
label="Solar Filters",
columns=4,
rows=3,
height="auto",
object_fit="contain",
show_label=False,
selected_index=3 # Default to 0211
)
# Hidden state to store the selected filter key
view_filter = gr.State(value="0211")
# Display selected filter info
view_filter_info = gr.Markdown("**Selected:** 211 ร
- Active regions")
gr.Markdown("#### ๐
Date Range Selection")
with gr.Row():
view_from_date = gr.Dropdown(
choices=self.get_available_dates(),
label="From Date",
info="Select starting date"
)
view_to_date = gr.Dropdown(
choices=self.get_available_dates(),
label="To Date",
info="Select ending date"
)
with gr.Row():
refresh_dates_btn = gr.Button("๐ Refresh Dates", size="sm")
load_images_btn = gr.Button("๐ Load Images", variant="primary")
view_status = gr.Textbox(label="Status", lines=3)
image_position = gr.Textbox(label="Position", value="0 / 0", interactive=False)
with gr.Column():
gr.Markdown("#### ๐ฎ Playback Controls")
with gr.Row():
first_btn = gr.Button("โฎ First", size="sm")
prev_btn = gr.Button("โช Prev", size="sm")
play_btn = gr.Button("โถ Play", variant="primary")
next_btn = gr.Button("Next โฉ", size="sm")
last_btn = gr.Button("Last โญ", size="sm")
view_image = gr.Image(label="Solar Image", type="filepath", height=600)
image_info = gr.Textbox(label="Image Information", interactive=False)
gr.Markdown("#### โก Speed Control")
with gr.Row():
speed_slider = gr.Slider(
minimum=0.5,
maximum=240.0,
value=120.0,
step=0.1,
label="Playback Speed (FPS)",
info="Frames per second during playback"
)
speed_display = gr.Textbox(
value="120.0 FPS",
label="Current Speed",
interactive=False,
scale=0
)
# Gallery selection event
view_filter_gallery.select(
fn=self.on_filter_gallery_select,
outputs=[view_filter, view_filter_info]
)
refresh_dates_btn.click(
fn=lambda res, filt: [gr.Dropdown(choices=self.get_available_dates(res, filt))] * 2,
inputs=[view_resolution, view_filter],
outputs=[view_from_date, view_to_date]
)
# Auto-refresh dates when resolution or filter changes
view_resolution.change(
fn=lambda res, filt: [gr.Dropdown(choices=self.get_available_dates(res, filt))] * 2,
inputs=[view_resolution, view_filter],
outputs=[view_from_date, view_to_date]
)
load_images_btn.click(
fn=self.load_images_for_date_range,
inputs=[view_from_date, view_to_date, view_resolution, view_filter],
outputs=[view_image, view_status, image_position]
)
# Navigation buttons
first_btn.click(
fn=lambda: self.navigate_image("first"),
outputs=[view_image, image_info, image_position, play_btn]
)
prev_btn.click(
fn=lambda: self.navigate_image("prev"),
outputs=[view_image, image_info, image_position, play_btn]
)
next_btn.click(
fn=lambda: self.navigate_image("next"),
outputs=[view_image, image_info, image_position, play_btn]
)
last_btn.click(
fn=lambda: self.navigate_image("last"),
outputs=[view_image, image_info, image_position, play_btn]
)
# Play/Pause button
play_btn.click(
fn=self.toggle_play,
outputs=[view_image, image_info, image_position, play_btn, speed_display]
)
# Speed control
speed_slider.change(
fn=self.update_play_speed,
inputs=[speed_slider],
outputs=[speed_display]
)
# Auto-update timer for playback (every 100ms)
play_timer = gr.Timer(0.1) # 100ms interval
play_timer.tick(
fn=self.update_playback,
outputs=[view_image, image_info, image_position, play_btn, speed_display]
)
# Create Video Tab
with gr.Tab("๐ฌ Create Videos"):
gr.Markdown("### Create MP4 Time-lapse Videos")
with gr.Row():
with gr.Column():
gr.Markdown("#### ๐๏ธ Quick Date Selection")
with gr.Row():
video_today_btn = gr.Button("Today", size="sm")
video_last3_btn = gr.Button("Last 3 Days", size="sm")
video_lastweek_btn = gr.Button("Last Week", size="sm")
gr.Markdown("#### ๐
Video Date Range")
video_start_date = gr.Textbox(
label="Start Date (YYYY-MM-DD)",
value=datetime.now().strftime("%Y-%m-%d")
)
video_end_date = gr.Textbox(
label="End Date (YYYY-MM-DD)",
value=datetime.now().strftime("%Y-%m-%d")
)
gr.Markdown("#### ๐ฌ Video Settings")
video_fps = gr.Slider(
minimum=1,
maximum=120,
value=10,
step=1,
label="FPS (Frames Per Second)",
info="Higher FPS = smoother but faster playback"
)
video_resolution = gr.Dropdown(
choices=["1024", "2048", "4096"],
value="1024",
label="Resolution"
)
gr.Markdown("#### ๐ Solar Filter Selection")
gr.Markdown("*Click on a thumbnail to select a solar filter*")
video_filter_gallery = gr.Gallery(
value=self.get_filter_gallery_data(),
label="Solar Filters",
columns=4,
rows=3,
height="auto",
object_fit="contain",
show_label=False,
selected_index=3 # Default to 0211
)
# Hidden state to store the selected filter key
video_filter = gr.State(value="0211")
# Display selected filter info
video_filter_info = gr.Markdown("**Selected:** 211 ร
- Active regions")
with gr.Row():
create_video_btn = gr.Button("๐ฌ Create Video for Date Range", variant="primary")
create_all_btn = gr.Button("๐ฌ Create Combined Video (All Available)")
with gr.Column():
video_output = gr.Textbox(label="Video Creation Status", lines=8)
video_player = gr.Video(label="Created Video", height=400)
# Video Playback Section
gr.Markdown("### ๐ฅ Play MP4 Videos")
with gr.Row():
with gr.Column():
gr.Markdown("#### ๐ Video Selection")
video_file_upload = gr.File(
label="Select MP4 File",
file_types=[".mp4"],
type="filepath"
)
# Or select from created videos
available_videos = gr.Dropdown(
choices=self.get_video_list(),
label="Or Select from Created Videos",
info="Choose from previously created videos"
)
refresh_videos_btn = gr.Button("๐ Refresh Video List", size="sm")
gr.Markdown("#### ๐ฎ Video Controls")
with gr.Row():
video_play_btn = gr.Button("โถ Play Video", variant="primary")
video_stop_btn = gr.Button("โน Stop")
video_fullscreen_btn = gr.Button("๐ณ Fullscreen")
video_info = gr.Textbox(label="Video Information", lines=3)
# Quick date button actions for video
video_today_btn.click(
fn=lambda: self.set_date_range(0),
outputs=[video_start_date, video_end_date]
)
video_last3_btn.click(
fn=lambda: self.set_date_range(2),
outputs=[video_start_date, video_end_date]
)
video_lastweek_btn.click(
fn=lambda: self.set_date_range(6),
outputs=[video_start_date, video_end_date]
)
# Gallery selection event for video tab
video_filter_gallery.select(
fn=self.on_filter_gallery_select,
outputs=[video_filter, video_filter_info]
)
create_video_btn.click(
fn=self.create_video,
inputs=[video_start_date, video_end_date, video_fps, video_resolution, video_filter],
outputs=[video_player, video_output]
)
# Settings Tab
with gr.Tab("โ๏ธ Settings"):
gr.Markdown("### Application Settings & System Information")
with gr.Row():
with gr.Column():
gr.Markdown("#### ๐ง Download Settings")
rate_limit = gr.Slider(
minimum=0.5,
maximum=5.0,
value=1.0,
step=0.1,
label="Rate Limit Delay (seconds)",
info="Delay between downloads to be respectful to NASA servers"
)
gr.Markdown("#### ๐ Custom Keyword Search")
gr.Markdown("*Customize search keywords for each solar filter. Leave empty to use defaults.*")
# Create custom keyword inputs for each filter
keyword_inputs = {}
for filter_num, data in list(self.filter_data.items())[:6]: # First 6 filters
with gr.Row():
gr.Markdown(f"**{data['name']}** ({filter_num})")
keyword_inputs[filter_num] = gr.Textbox(
value=filter_num,
placeholder=f"Default: {filter_num}",
scale=2
)
with gr.Row():
reset_keywords_btn = gr.Button("๐ Reset to Defaults", size="sm")
apply_keywords_btn = gr.Button("โ
Apply Keywords", variant="primary")
keyword_status = gr.Textbox(label="Keyword Status", lines=2)
with gr.Column():
gr.Markdown("#### ๐ Data Management")
with gr.Row():
open_data_btn = gr.Button("๐ Open Data Folder")
cleanup_btn = gr.Button("๐งน Clean Up Corrupted Files")
data_management_output = gr.Textbox(label="Data Management Status", lines=2)
gr.Markdown("#### ๐ฅ๏ธ System Information")
system_info = gr.Markdown(self.get_system_info())
refresh_info_btn = gr.Button("๐ Refresh System Info")
# Keyword management
reset_keywords_btn.click(
fn=self.reset_custom_keywords,
outputs=[keyword_status]
)
# Data management
open_data_btn.click(
fn=self.open_data_folder,
outputs=[data_management_output]
)
cleanup_btn.click(
fn=self.cleanup_corrupted_files,
outputs=[data_management_output]
)
refresh_info_btn.click(
fn=self.get_system_info,
outputs=[system_info]
)
# Video controls
refresh_videos_btn.click(
fn=self.get_video_list,
outputs=[available_videos]
)
# About Tab
with gr.Tab("โน๏ธ About"):
gr.Markdown("""
## About NASA Solar Image Downloader
This comprehensive web application downloads and processes images from NASA's Solar Dynamics Observatory (SDO).
### ๐ Features
- **Download Management**: Bulk download solar images for any date range (max 7 days in cloud)
- **Image Viewer**: Browse images with full playback controls (First, Previous, Next, Last)
- **Video Creation**: Create time-lapse MP4 videos with customizable FPS (limited in cloud)
- **Multiple Filters**: 12 different wavelengths and composite filters
- **High Resolution**: Support for 1024, 2048, and 4096 pixel images
- **Custom Keywords**: Advanced search customization
- **Progress Tracking**: Real-time progress for all operations
### ๐ฌ Solar Filters Explained
**Individual Wavelengths:**
- **193 ร
**: Shows coronal loops and hot active regions
- **304 ร
**: Reveals the chromosphere and filament channels
- **171 ร
**: Displays quiet corona and coronal holes
- **211 ร
**: Highlights active regions and hot plasma
- **131 ร
**: Shows flaring regions and very hot plasma
- **335 ร
**: Reveals active region cores
- **94 ร
**: Shows extremely hot plasma and flare ribbons
- **1600 ร
**: Displays transition region and upper photosphere
- **1700 ร
**: Shows temperature minimum and photosphere
**Composite Filters:**
- **094+335+193**: Multi-wavelength view of hot plasma structures
- **304+211+171**: Comprehensive view from chromosphere to corona
- **211+193+171**: Active regions with coronal context
### ๐ Quick Start Guide
1. **Download Images**: Select date range, choose filter, click download
2. **View Images**: Load images and use playback controls to browse
3. **Create Videos**: Set date range and FPS, create time-lapse videos (limited in cloud)
4. **Customize**: Use Settings tab for advanced configuration
### ๐ Data Source
All images are sourced from NASA's Solar Dynamics Observatory (SDO), which provides continuous observations of the Sun in multiple wavelengths.
**๐ Created by Andy Kong**
---
*This cloud version provides the same functionality as the desktop version but with some limitations for cloud deployment.*
""")
return app
def launch(self, share=False, server_port=7860):
"""Launch the Gradio interface."""
app = self.create_interface()
app.launch(share=share, server_port=server_port)
def main():
"""Main application entry point."""
try:
print("๐ Starting NASA Solar Image Downloader (Hugging Face Spaces)")
print("=" * 60)
# Create and launch the Gradio app
hf_app = NASADownloaderHF()
# Launch for HF Spaces
hf_app.launch(share=False, server_port=None)
except Exception as e:
print(f"โ Error starting application: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main() |