-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1066 lines (887 loc) · 40.9 KB
/
app.py
File metadata and controls
1066 lines (887 loc) · 40.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
from PIL import Image
import io
import base64
import requests
import re
import os
from datetime import datetime, timedelta
from dotenv import load_dotenv
from openai import OpenAI
from openai import AuthenticationError, RateLimitError, APIError
# Load environment variables from .env file
load_dotenv()
# Page configuration
st.set_page_config(
page_title="SpaceExplainer AI",
page_icon="🔭",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for better spacing and design
st.markdown("""
<style>
.main > div {
padding-top: 2rem;
}
.stMarkdown h1 {
margin-bottom: 1rem;
}
.stMarkdown h2 {
margin-top: 2rem;
margin-bottom: 1rem;
}
.stMarkdown h3 {
margin-top: 1.5rem;
margin-bottom: 0.75rem;
}
.stButton > button {
width: 100%;
margin-top: 0.5rem;
}
.stSidebar .element-container {
margin-bottom: 1.5rem;
}
@media (max-width: 768px) {
.main > div {
padding-top: 1rem;
}
}
</style>
""", unsafe_allow_html=True)
# Title and description
st.title("🔭 SpaceExplainer AI")
st.markdown("**Upload any space image to learn what you're looking at with AI + NASA data**")
st.markdown("---")
# Initialize session state
if 'uploaded_image' not in st.session_state:
st.session_state.uploaded_image = None
if 'api_key' not in st.session_state:
st.session_state.api_key = None
if 'base64_image' not in st.session_state:
st.session_state.base64_image = None
if 'ai_response' not in st.session_state:
st.session_state.ai_response = None
if 'current_filename' not in st.session_state:
st.session_state.current_filename = None
@st.cache_data(ttl=3600) # Cache for 1 hour
def search_nasa_images(search_term: str) -> list:
"""
Search NASA's Image and Video Library for relevant space images.
This function queries NASA's public API to find images matching the search term.
Results are cached for 1 hour to reduce API calls and improve performance.
Args:
search_term (str): The search query (e.g., "Crab Nebula", "Mars", "nebula art").
Can be a celestial object name or general space term.
Returns:
list: A list of dictionaries, each containing:
- title (str): Image title
- description (str): Truncated description (max 300 chars)
- image_url (str): URL to the image file
- nasa_id (str): NASA's unique identifier for the image
- nasa_url (str): Link to NASA's detail page for the image
Returns empty list if no results found or on error.
Example:
>>> results = search_nasa_images("Crab Nebula")
>>> print(results[0]['title'])
'Crab Nebula'
Note:
Uses NASA's public API (no authentication required).
Returns top 3 results maximum.
"""
try:
# NASA Image and Video Library API
url = f"https://images-api.nasa.gov/search"
params = {
"q": search_term,
"media_type": "image",
"page": 1,
"page_size": 3 # Get top 3 results
}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
results = []
if "collection" in data and "items" in data["collection"]:
for item in data["collection"]["items"][:3]: # Top 3
# Extract image data
nasa_id = item.get("data", [{}])[0].get("nasa_id", "")
title = item.get("data", [{}])[0].get("title", "Untitled")
description = item.get("data", [{}])[0].get("description", "")
# Get image URL (prefer JPEG)
links = item.get("links", [])
image_url = ""
for link in links:
if link.get("render") == "image" and "jpg" in link.get("href", ""):
image_url = link["href"]
break
if not image_url and links:
image_url = links[0].get("href", "")
if image_url:
results.append({
"title": title,
"description": description[:300] + "..." if len(description) > 300 else description,
"image_url": image_url,
"nasa_id": nasa_id,
"nasa_url": f"https://images.nasa.gov/details-{nasa_id}"
})
return results
except Exception as e:
st.warning(f"NASA search error: {e}")
return []
@st.cache_data(ttl=3600) # Cache for 1 hour
def get_today_apod() -> dict | None:
"""
Retrieve today's Astronomy Picture of the Day (APOD) from NASA.
This function fetches the current day's APOD as a fallback when no
relevant images are found in the NASA Image Library search.
Returns:
dict | None: APOD data dictionary containing:
- title (str): APOD title
- explanation (str): Detailed explanation
- url (str): Image URL
- hdurl (str): High-definition image URL (if available)
- date (str): Date in YYYY-MM-DD format
- media_type (str): "image" or "video"
Returns None if fetch fails or API error occurs.
Example:
>>> apod = get_today_apod()
>>> print(apod['title'])
'Today's Astronomy Picture of the Day'
Note:
Uses NASA's DEMO_KEY (no authentication required).
Results are cached for 1 hour.
"""
api_key = "DEMO_KEY"
base_url = "https://api.nasa.gov/planetary/apod"
try:
params = {"api_key": api_key}
response = requests.get(base_url, params=params, timeout=5)
if response.status_code == 200:
return response.json()
else:
return None
except Exception as e:
st.warning(f"Could not fetch NASA APOD: {str(e)}")
return None
def display_apod(apod_data: dict) -> None:
"""
Display Astronomy Picture of the Day (APOD) data in Streamlit.
This function renders APOD information including the image, title, date,
explanation, and a link to NASA's website. Used as a fallback when
NASA Image Library search returns no results.
Args:
apod_data (dict): Dictionary containing APOD data with keys:
- title (str): APOD title
- explanation (str): Detailed explanation
- url (str): Image URL
- hdurl (str, optional): High-definition image URL
- date (str): Date in YYYY-MM-DD format
- media_type (str): "image" or "video"
Returns:
None: This function only renders UI elements.
Example:
>>> apod = get_today_apod()
>>> display_apod(apod)
# Renders APOD in Streamlit interface
Note:
Only displays if media_type is "image".
Automatically converts date to APOD URL format.
"""
if not apod_data:
return
# Display NASA image
if apod_data.get("media_type") == "image":
image_url = apod_data.get("hdurl") or apod_data.get("url")
if image_url:
st.image(image_url, caption=apod_data.get("title", "NASA APOD"), use_container_width=True)
# Display title and date
st.markdown(f"### {apod_data.get('title', 'NASA Astronomy Picture of the Day')}")
if apod_data.get("date"):
st.caption(f"📅 Date: {apod_data.get('date')}")
# Display explanation
if apod_data.get("explanation"):
st.markdown("**Official Explanation:**")
st.markdown(apod_data.get("explanation"))
# Link to NASA website
if apod_data.get("date"):
apod_date = apod_data.get("date")
# Convert YYYY-MM-DD to YYMMDD format for APOD URL
date_parts = apod_date.split('-')
if len(date_parts) == 3:
year_short = date_parts[0][-2:] # Last 2 digits of year
nasa_url = f"https://apod.nasa.gov/apod/ap{year_short}{date_parts[1]}{date_parts[2]}.html"
st.markdown(f'<a href="{nasa_url}" target="_blank">🔗 View on NASA website</a>', unsafe_allow_html=True)
st.caption("💫 Today's Astronomy Picture of the Day")
def extract_educational_info(ai_response: str) -> dict:
"""
Extract educational information from AI analysis text.
Parses the AI response to extract key educational facts including object type,
visibility requirements, viewing season, and distance information. Used to
populate the Quick Facts sidebar.
Args:
ai_response (str): The full AI analysis text response.
Returns:
dict: Dictionary containing educational information:
- object_type (str): Type of celestial object (e.g., "Nebula", "Galaxy")
- visibility (str): Visibility rating emoji ("🌟", "🌟🌟", "🌟🌟🌟")
- season (str): Best viewing season (e.g., "Winter", "Year-round")
- distance (str): Distance information or "Unknown"
- distance_category (str): "Solar System", "Milky Way", "Deep Space", or "Unknown"
Example:
>>> info = extract_educational_info(ai_response)
>>> print(info['object_type'])
'Nebula'
>>> print(info['visibility'])
'🌟🌟'
Note:
Returns default values if ai_response is None or empty.
Uses keyword matching to extract information.
"""
if not ai_response:
return {
"object_type": "Unknown",
"visibility": "🌟",
"season": "Year-round",
"distance": "Unknown",
"distance_category": "Unknown"
}
info = {
"object_type": "Unknown",
"visibility": "🌟",
"season": "Year-round",
"distance": "Unknown",
"distance_category": "Unknown"
}
text_lower = ai_response.lower()
# Extract object type from Identification section
object_types = {
"nebula": ["nebula", "nebulae"],
"galaxy": ["galaxy", "galaxies"],
"planet": ["planet", "planets"],
"star": ["star", "stars", "stellar"],
"cluster": ["cluster", "star cluster"],
"supernova": ["supernova", "supernovae"],
"comet": ["comet", "comets"],
"asteroid": ["asteroid", "asteroids"],
"moon": ["moon", "satellite"],
"constellation": ["constellation", "constellations"]
}
for obj_type, keywords in object_types.items():
if any(keyword in text_lower for keyword in keywords):
info["object_type"] = obj_type.title()
break
# Extract visibility/equipment from Observation Tips
if "naked eye" in text_lower or "unaided eye" in text_lower:
info["visibility"] = "🌟"
elif "binoculars" in text_lower or "binocular" in text_lower:
info["visibility"] = "🌟🌟"
elif "telescope" in text_lower:
info["visibility"] = "🌟🌟🌟"
# Extract distance from Key Facts
distance_keywords = {
"light-year": ["light-year", "light years", "ly"],
"parsec": ["parsec", "pc"],
"astronomical unit": ["au", "astronomical unit"],
"kilometer": ["km", "kilometer"],
"million": ["million"],
"billion": ["billion"]
}
# Try to find distance mentions
lines = ai_response.split('\n')
for line in lines:
line_lower = line.lower()
if any(keyword in line_lower for keyword in ["distance", "away", "located"]):
# Extract numbers and units
distance_match = re.search(r'(\d+(?:[.,]\d+)?)\s*(light-year|light years|ly|parsec|pc|au|km|kilometer|million|billion)', line_lower)
if distance_match:
info["distance"] = line.strip()[:50] # First 50 chars
break
# Determine distance category
if "solar system" in text_lower or "au" in text_lower or "km" in text_lower:
info["distance_category"] = "Solar System"
elif "light-year" in text_lower or "ly" in text_lower:
# Check if it's within Milky Way (typically < 100,000 ly)
if any(x in text_lower for x in ["thousand", "kly", "10", "100"]):
info["distance_category"] = "Milky Way"
else:
info["distance_category"] = "Deep Space"
else:
info["distance_category"] = "Unknown"
# Extract season from Observation Tips
seasons = ["winter", "spring", "summer", "fall", "autumn"]
for season in seasons:
if season in text_lower:
info["season"] = season.title()
break
return info
def extract_confidence_level(ai_response: str) -> str:
"""
Determine confidence level of AI analysis based on keyword detection.
Analyzes the AI response text for indicators of image authenticity and
analysis certainty. Used to display confidence indicators and adjust
NASA search behavior for artistic/synthetic images.
Args:
ai_response (str): The full AI analysis text response.
Returns:
str: Confidence level, one of:
- "high": Clear real astronomical image (high confidence keywords found)
- "medium": Possible artistic/synthetic (uncertainty indicators found)
- "low": Uncertain or likely not real (artistic/synthetic keywords found)
Example:
>>> confidence = extract_confidence_level(ai_response)
>>> print(confidence)
'high'
Note:
Defaults to "medium" if no clear indicators found.
Low confidence triggers: artistic, synthetic, AI-generated, not real, fictional
High confidence triggers: clear, definite, confirmed, real, actual, authentic
"""
if not ai_response:
return "medium"
text_lower = ai_response.lower()
# Low confidence indicators
low_confidence_keywords = [
"artistic", "art", "synthetic", "ai-generated", "generated", "artificial",
"not real", "fictional", "illustration", "rendering", "simulation",
"uncertain", "unclear", "unlikely", "possibly", "may be", "might be",
"appears to be", "seems", "low quality", "poor quality", "blurry"
]
# Medium confidence indicators
medium_confidence_keywords = [
"possibly", "likely", "probably", "appears", "seems like", "could be",
"resembles", "similar to"
]
# High confidence indicators
high_confidence_keywords = [
"clear", "definite", "confirmed", "certain", "real", "actual",
"authentic", "genuine", "verified"
]
# Check for low confidence
low_count = sum(1 for keyword in low_confidence_keywords if keyword in text_lower)
medium_count = sum(1 for keyword in medium_confidence_keywords if keyword in text_lower)
high_count = sum(1 for keyword in high_confidence_keywords if keyword in text_lower)
# Determine confidence level
if low_count >= 2 or any(keyword in text_lower for keyword in ["artistic", "synthetic", "ai-generated", "not real", "fictional"]):
return "low"
elif low_count >= 1 or medium_count >= 2:
return "medium"
elif high_count >= 2 and low_count == 0:
return "high"
else:
# Default to medium if unclear
return "medium"
def extract_object_name(ai_response: str) -> str | None:
"""
Extract the main celestial object name from AI analysis text.
This function specifically looks for the **Identification** section in the AI
response and extracts the first proper celestial object name. It cleans the
extracted name by removing prefixes, suffixes, and parenthetical notes.
Args:
ai_response (str): The full AI analysis text response.
Returns:
str | None: Clean object name (e.g., "Crab Nebula", "Rosette Nebula")
or None if no object name can be extracted.
Example:
>>> name = extract_object_name("**Identification**\\nCelestial Object: Crab Nebula")
>>> print(name)
'Crab Nebula'
Note:
- Removes prefixes: "Celestial Object:", "Type:", "Object:", "Name:"
- Removes parenthetical notes: "(M1)", "(NGC 1952)"
- Extracts 2-4 words that form the object name
- Falls back to searching entire response if Identification section not found
- Uses celestial keywords (nebula, galaxy, cluster, etc.) to identify object names
"""
if not ai_response:
return None
try:
lines = ai_response.split('\n')
# Step 1: Look specifically for **Identification** section
identification_idx = None
for i, line in enumerate(lines):
# Look for exact match or variations of Identification header
line_lower = line.lower().strip()
if line_lower == '**identification**' or line_lower == 'identification' or line_lower.startswith('**identification'):
identification_idx = i
break
if identification_idx is not None:
# Step 2: Extract the first proper celestial object name after Identification
# Look at the next few lines after the header
for i in range(identification_idx + 1, min(identification_idx + 5, len(lines))):
line = lines[i].strip()
if not line or line.startswith('#'):
continue
# Clean the line: remove common prefixes and suffixes
cleaned_line = line
# Remove markdown formatting
cleaned_line = re.sub(r'\*\*', '', cleaned_line)
cleaned_line = re.sub(r'\*', '', cleaned_line)
# Remove common prefixes like "Celestial Object:", "Type:", "Object:", etc.
prefixes_to_remove = [
r'^celestial object:\s*',
r'^type:\s*',
r'^object:\s*',
r'^name:\s*',
r'^this is\s+',
r'^this\s+',
]
for prefix in prefixes_to_remove:
cleaned_line = re.sub(prefix, '', cleaned_line, flags=re.IGNORECASE)
# Remove parenthetical notes (e.g., "Crab Nebula (M1)")
cleaned_line = re.sub(r'\([^)]*\)', '', cleaned_line)
# Remove trailing colons and extra punctuation
cleaned_line = re.sub(r'[:;,\-]+$', '', cleaned_line)
# Extract the first 2-4 words that look like a celestial object name
words = cleaned_line.split()
if not words:
continue
# Look for celestial object keywords to determine where the name ends
celestial_keywords = [
'nebula', 'nebulae', 'galaxy', 'galaxies', 'cluster', 'star', 'stars',
'supernova', 'supernovae', 'comet', 'comets', 'asteroid', 'asteroids',
'planet', 'planets', 'moon', 'satellite', 'constellation', 'constellations',
'remnant', 'remnants', 'cloud', 'clouds', 'system', 'systems'
]
# Find where the object name likely ends (at a keyword or after 2-4 words)
object_name_words = []
found_keyword = False
for word in words[:6]: # Check first 6 words max
word_lower = word.lower().strip('.,;:!?')
object_name_words.append(word_lower)
# If we find a celestial keyword, include it and stop
if any(keyword in word_lower for keyword in celestial_keywords):
found_keyword = True
break
# If we have 2-4 words and the next word doesn't look like part of the name, stop
if len(object_name_words) >= 2:
# Check if next word is a common separator word
if len(words) > len(object_name_words):
next_word = words[len(object_name_words)].lower()
if next_word in ['is', 'a', 'an', 'the', 'type', 'located', 'found', 'known']:
break
if object_name_words:
# Join the words and clean up
object_name = ' '.join(object_name_words)
object_name = re.sub(r'[^\w\s-]', '', object_name) # Remove special chars except hyphens
object_name = ' '.join(object_name.split()) # Normalize whitespace
object_name = object_name.strip().title() # Title case for proper names
if len(object_name) > 2: # Valid name should be at least 3 chars
return object_name
# Step 3: Fallback - search entire response for celestial object patterns
celestial_keywords = [
'nebula', 'nebulae', 'galaxy', 'galaxies', 'cluster', 'star', 'stars',
'supernova', 'supernovae', 'comet', 'comets', 'asteroid', 'asteroids',
'planet', 'planets', 'moon', 'satellite', 'constellation', 'constellations'
]
# Look for patterns like "X Nebula", "X Galaxy", etc. in first few lines
for line in lines[:10]: # Check first 10 lines
line_lower = line.lower()
for keyword in celestial_keywords:
# Look for pattern: word(s) + keyword
pattern = r'(\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+' + re.escape(keyword)
match = re.search(pattern, line, re.IGNORECASE)
if match:
object_name = match.group(1) + ' ' + keyword
# Clean it up
object_name = re.sub(r'[^\w\s-]', '', object_name)
object_name = ' '.join(object_name.split())
if len(object_name) > 5: # Valid name
return object_name.strip().title()
# Last resort: return first 2-3 words if they contain a celestial keyword
first_line = lines[0].strip() if lines else ""
if first_line:
words = first_line.split()[:4]
for i, word in enumerate(words):
word_lower = word.lower().strip('.,;:!?')
if any(keyword in word_lower for keyword in celestial_keywords):
# Take this word and the word before it (if exists)
start_idx = max(0, i - 1)
name_parts = words[start_idx:i+1]
object_name = ' '.join(name_parts)
object_name = re.sub(r'[^\w\s-]', '', object_name)
object_name = ' '.join(object_name.split())
if len(object_name) > 3:
return object_name.strip().title()
return None
except Exception as e:
# Log error but don't crash - return None to trigger fallback
st.warning(f"Error extracting object name: {str(e)}")
return None
@st.cache_data
def image_to_base64(uploaded_file) -> str:
"""
Convert uploaded image to base64 format for OpenAI Vision API.
This function processes uploaded images by converting them to RGB mode,
resizing if necessary (max width 2000px), and encoding to base64.
Results are cached to avoid reprocessing the same file.
Args:
uploaded_file: Streamlit uploaded file object (from st.file_uploader).
Must be a valid image file (JPG, JPEG, PNG).
Returns:
str: Base64-encoded data URI string in format:
"data:image/jpeg;base64,{base64_string}"
Example:
>>> base64_str = image_to_base64(uploaded_file)
>>> print(base64_str[:30])
'data:image/jpeg;base64,/9j/4AAQ...'
Note:
- Automatically converts RGBA/P mode images to RGB
- Resizes images wider than 2000px (maintains aspect ratio)
- Uses JPEG format with 85% quality
- Cached by file content to avoid reprocessing
- Raises exception if file cannot be processed
"""
# Read file content for caching key
file_bytes = uploaded_file.read()
uploaded_file.seek(0) # Reset file pointer
# Open image with PIL
image = Image.open(io.BytesIO(file_bytes))
# Convert to RGB mode if needed (handles RGBA, P, etc.)
if image.mode != 'RGB':
image = image.convert('RGB')
# Resize if width > 2000px (maintain aspect ratio)
if image.width > 2000:
ratio = 2000 / image.width
new_height = int(image.height * ratio)
image = image.resize((2000, new_height), Image.Resampling.LANCZOS)
# Convert to bytes
buffer = io.BytesIO()
image.save(buffer, format='JPEG', quality=85)
image_bytes = buffer.getvalue()
# Encode to base64
base64_str = base64.b64encode(image_bytes).decode('utf-8')
# Return data URI format
return f"data:image/jpeg;base64,{base64_str}"
# Sidebar
# Try to get API key from .env file first
env_api_key = os.environ.get("OPENAI_API_KEY", "")
with st.sidebar:
st.header("⚙️ Configuration")
# Show status about .env key
if env_api_key:
st.info("🔑 Key loaded from .env file")
api_key_input = st.text_input(
"OpenAI API Key",
type="password",
value=env_api_key, # Pre-fill with .env key
placeholder="sk-...",
help="Automatically loaded from .env file. You can override if needed."
)
# Store the key in session state
# Use the input if provided, otherwise use .env key
if api_key_input:
st.session_state.api_key = api_key_input
if api_key_input != env_api_key:
st.success("✅ Using custom key")
else:
# Use .env key if available, otherwise None
st.session_state.api_key = env_api_key if env_api_key else None
st.markdown("---")
st.markdown("""
**💡 Need an API key?**
Get free credits at <a href="https://platform.openai.com" target="_blank">platform.openai.com</a>
Create an account and generate your API key to start using SpaceExplainer AI.
""")
# Quick Facts section
if st.session_state.ai_response is not None:
st.markdown("---")
st.header("📚 Quick Facts")
# Extract educational info
edu_info = extract_educational_info(st.session_state.ai_response)
st.markdown(f"**Type:** {edu_info['object_type']}")
st.markdown(f"**Visibility:** {edu_info['visibility']}")
if edu_info['visibility'] == "🌟":
st.caption("Naked eye")
elif edu_info['visibility'] == "🌟🌟":
st.caption("Binoculars recommended")
else:
st.caption("Telescope required")
st.markdown(f"**Season:** {edu_info['season']}")
st.markdown(f"**Distance:** {edu_info['distance_category']}")
if edu_info['distance'] != "Unknown":
st.caption(edu_info['distance'][:60])
# Developer Tools
st.markdown("---")
st.header("🛠️ Developer Tools")
col_clear1, col_clear2 = st.columns(2)
with col_clear1:
if st.button("🗑️ Clear Cache", use_container_width=True):
st.cache_data.clear()
st.success("Cache cleared!")
st.rerun()
with col_clear2:
if st.button("🔄 Clear All", use_container_width=True):
# Clear all session state
for key in list(st.session_state.keys()):
del st.session_state[key]
st.cache_data.clear()
st.success("All data cleared!")
st.rerun()
# About section
st.markdown("---")
st.header("ℹ️ About")
with st.expander("How it works"):
st.markdown("""
1. **Upload** a space image (JPG/PNG)
2. **AI Analysis** - GPT-4 Vision analyzes the image
3. **NASA Context** - Official APOD data is fetched
4. **Learn More** - Get educational resources
The app uses OpenAI's GPT-4 Vision model to identify
celestial objects and NASA's APOD API for official context.
""")
with st.expander("Tech Stack"):
st.markdown("""
- **Frontend**: Streamlit
- **AI**: OpenAI GPT-4 Vision
- **Data**: NASA APOD API
- **Image Processing**: PIL/Pillow
- **Language**: Python 3.8+
""")
with st.expander("Disclaimer"):
st.markdown("""
⚠️ **AI Accuracy Notice**
While AI analysis is powerful, it may not always be 100% accurate.
Always verify important information with official sources.
This tool is for educational purposes only.
""")
st.markdown("---")
st.markdown("""
**🔗 Links**
- <a href="https://github.com/yourusername/spaceexplainer-ai" target="_blank">GitHub Repository</a> (Update with your repo)
- <a href="https://github.com/yourusername/spaceexplainer-ai/issues" target="_blank">Report Issue</a>
""")
# Main layout with columns
col1, col2 = st.columns([1, 1])
with col1:
st.subheader("📤 Upload Image")
# File uploader
uploaded_file = st.file_uploader(
"Choose an image file",
type=['jpg', 'jpeg', 'png'],
help="Upload a JPG or PNG image to analyze"
)
# Store uploaded image in session state and process to base64
if uploaded_file is not None:
# Clear previous analysis if new image is uploaded
if st.session_state.current_filename != uploaded_file.name:
st.session_state.ai_response = None
st.session_state.uploaded_image = uploaded_file
st.session_state.current_filename = uploaded_file.name
# Process image to base64
st.session_state.base64_image = image_to_base64(uploaded_file)
st.success("✓ Image processed and ready for AI analysis")
else:
st.session_state.uploaded_image = None
st.session_state.base64_image = None
st.session_state.ai_response = None
st.session_state.current_filename = None
with col2:
st.subheader("🖼️ Preview")
# Display uploaded image
if st.session_state.uploaded_image is not None:
image = Image.open(st.session_state.uploaded_image)
st.image(image, caption="Uploaded Image", use_container_width=True)
else:
st.info("👆 Upload an image to see preview")
# Spacing
st.markdown("---")
# Analyze button section
st.subheader("🤖 AI Analysis")
# Button (disabled if no image uploaded or no API key)
analyze_button = st.button(
"Analyze with AI",
type="primary",
disabled=st.session_state.uploaded_image is None or st.session_state.api_key is None,
use_container_width=True
)
if analyze_button and st.session_state.uploaded_image is not None and st.session_state.api_key is not None:
with st.spinner("🔭 Analyzing image with AI..."):
try:
# Initialize OpenAI client
client = OpenAI(api_key=st.session_state.api_key)
# Detailed prompt for NASA educator style analysis
prompt_text = """You are a NASA educator. Analyze this space image and provide:
1. **Identification**: What celestial object or phenomenon is this? Be specific. IMPORTANT: If the image appears to be artistic, AI-generated, synthetic, or low-quality, clearly state this and express appropriate uncertainty. Do not identify fictional or artistic images as real astronomical objects.
2. **Key Facts**: 3-5 bullet points about distance, size, significance, or discovery. If the image is artistic/synthetic, note this instead.
3. **Observation Tips**: How and when can this be observed? Equipment needed? Skip if image is not a real astronomical object.
4. **Scientific Context**: Why is this object important to astronomy? If artistic/synthetic, explain why this might be misleading.
Format your response with clear sections using Markdown. Be accurate and inspiring. Always be honest about image authenticity."""
# Call OpenAI Vision API
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": prompt_text},
{"type": "image_url", "image_url": {"url": st.session_state.base64_image}}
]
}
],
max_tokens=800
)
# Extract and store response
st.session_state.ai_response = response.choices[0].message.content
except AuthenticationError:
st.error("❌ Invalid API key. Please check your API key and try again.")
st.info("Make sure your API key starts with 'sk-' and is valid.")
except RateLimitError:
st.error("❌ Rate limit exceeded. Please wait a moment and try again.")
st.info("You may have reached your API usage limit. Check your OpenAI account for details.")
except APIError as e:
st.error(f"❌ OpenAI API error: {str(e)}")
st.info("Please check your API key and account status, then try again.")
except Exception as e:
st.error(f"❌ Error during analysis: {str(e)}")
st.info("Please check your API key and try again.")
# Display AI analysis result if available
if st.session_state.ai_response is not None:
st.success("✅ Analysis Complete!")
st.markdown("---")
# Extract confidence level
confidence_level = extract_confidence_level(st.session_state.ai_response)
# Display confidence indicator
if confidence_level == "high":
st.markdown("**Confidence Level:** 🟢 High (Clear real astronomical image)")
elif confidence_level == "medium":
st.markdown("**Confidence Level:** 🟡 Medium (Possible artistic/synthetic)")
else:
st.markdown("**Confidence Level:** 🔴 Low (Uncertain or likely not real)")
st.warning("⚠️ Note: This identification has lower confidence due to image quality or artistic nature.")
st.markdown("---")
# Display formatted analysis with markdown in columns for better layout
col_analysis, col_sidebar = st.columns([2, 1])
with col_analysis:
st.markdown(st.session_state.ai_response)
with col_sidebar:
st.markdown("### 📚 Quick Facts")
edu_info = extract_educational_info(st.session_state.ai_response)
st.markdown(f"**Type:** {edu_info['object_type']}")
st.markdown(f"**Visibility:** {edu_info['visibility']}")
if edu_info['visibility'] == "🌟":
st.caption("👁️ Naked eye")
elif edu_info['visibility'] == "🌟🌟":
st.caption("🔭 Binoculars")
else:
st.caption("🔭🔭 Telescope")
st.markdown(f"**Season:** {edu_info['season']}")
st.markdown(f"**Distance:** {edu_info['distance_category']}")
if edu_info['distance'] != "Unknown":
st.caption(edu_info['distance'][:60] + "...")
st.markdown("---")
# Action buttons and copy section
col_buttons, col_info = st.columns([2, 1])
with col_buttons:
col_copy, col_clear = st.columns(2)
with col_copy:
st.markdown("**📋 Copy Analysis Text**")
st.code(st.session_state.ai_response, language="markdown")
st.caption("Click the copy button above or select and copy the text")
with col_clear:
st.markdown("**🔄 New Analysis**")
if st.button("Try Another Image", use_container_width=True, type="secondary"):
st.session_state.ai_response = None
st.rerun()
st.caption("Clear analysis but keep current image")
with col_info:
st.markdown("---")
st.caption("💡 Note: This analysis uses OpenAI credits.")
# NASA Image Library Integration
st.markdown("---")
st.subheader("🌌 NASA Image Library Results")
# Adjust search based on confidence level
confidence_level = extract_confidence_level(st.session_state.ai_response)
search_term = extract_object_name(st.session_state.ai_response)
if confidence_level == "low":
# For low confidence (artistic/synthetic), search for general space art or the object type
if search_term:
# Try to get object type for better search
edu_info = extract_educational_info(st.session_state.ai_response)
object_type = edu_info.get('object_type', '').lower()
if object_type in ['nebula', 'galaxy', 'cluster', 'star']:
search_term = f"{object_type} art"
else:
search_term = "space art"
else:
search_term = "space art"
st.info("🎨 Showing artistic/illustrated space images due to low confidence in image authenticity.")
if search_term:
with st.spinner(f"🔍 Searching NASA for '{search_term}'..."):
nasa_results = search_nasa_images(search_term)
if nasa_results:
for i, result in enumerate(nasa_results):
with st.expander(f"📷 {result['title']}", expanded=(i==0)):
col1, col2 = st.columns([1, 2])
with col1:
st.image(result['image_url'], use_container_width=True)
with col2:
st.markdown(f"**NASA ID:** {result['nasa_id']}")
st.markdown(f"**Description:** {result['description']}")
nasa_link = result['nasa_url']
st.markdown(f'<a href="{nasa_link}" target="_blank">🔗 View on NASA Website</a>', unsafe_allow_html=True)
else:
st.info(f"📡 No NASA images found for '{search_term}'. Showing today's Astronomy Picture of the Day instead.")
# Fallback to today's APOD
apod_data = get_today_apod()
if apod_data:
display_apod(apod_data)
else:
st.info("📡 Could not extract search term. Showing today's Astronomy Picture of the Day instead.")
# Fallback to today's APOD
apod_data = get_today_apod()