MohammedSameerSyed commited on
Commit
2e1f606
Β·
verified Β·
1 Parent(s): 1f5d71a

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +189 -58
app.py CHANGED
@@ -33,7 +33,7 @@ class CometDetectorV3:
33
 
34
  fits_files = sorted(Path(tmpdir).rglob('*.fts')) + sorted(Path(tmpdir).rglob('*.fits'))
35
 
36
- for fpath in fits_files:
37
  try:
38
  with fits.open(fpath) as hdul:
39
  img = hdul[0].data.astype(np.float32)
@@ -56,20 +56,12 @@ class CometDetectorV3:
56
  return max_proj
57
 
58
  def classify_image(self, max_proj):
59
- # Normalize
60
  img = (max_proj - max_proj.min()) / (max_proj.max() - max_proj.min() + 1e-8)
61
-
62
- # Resize to 512x512
63
  img = cv2.resize(img, (512, 512))
64
-
65
- # To RGB
66
  img_rgb = np.stack([img, img, img], axis=0)
67
  img_tensor = torch.FloatTensor(img_rgb).unsqueeze(0).to(self.device)
68
-
69
- # Normalize
70
  img_tensor = self.transform(img_tensor)
71
 
72
- # Predict
73
  with torch.no_grad():
74
  output = self.model(img_tensor)
75
  probs = torch.softmax(output, dim=1)
@@ -80,100 +72,235 @@ class CometDetectorV3:
80
 
81
  def process_and_visualize(self, zip_file):
82
  try:
 
 
 
83
  images = self.load_fits_from_zip(zip_file.name)
84
 
85
  if len(images) < 2:
86
- return None, "❌ Need at least 2 FITS images"
87
 
88
  max_proj = self.create_difference_images(images)
89
  pred_class, confidence = self.classify_image(max_proj)
90
 
91
- # Visualize
92
- fig, axes = plt.subplots(1, 2, figsize=(14, 6))
 
 
93
 
 
94
  axes[0].imshow(images[0], cmap='gray')
95
- axes[0].set_title('First Image in Sequence')
 
96
  axes[0].axis('off')
97
 
 
98
  axes[1].imshow(max_proj, cmap='hot')
99
  if pred_class == 1:
100
- axes[1].set_title('⭐ COMET DETECTED', fontsize=14, color='green', weight='bold')
 
101
  else:
102
- axes[1].set_title('Background - No Comet', fontsize=14)
 
103
  axes[1].axis('off')
104
 
105
  plt.tight_layout()
106
 
107
- # Summary
108
  if pred_class == 1:
109
- summary = f"## βœ… **COMET DETECTED!**\n\n"
110
- summary += f"**Confidence:** {confidence:.1%}\n\n"
111
- summary += "This sequence shows signs of comet activity.\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  else:
113
- summary = f"## ❌ **No Comet Detected**\n\n"
114
- summary += f"**Confidence:** {confidence:.1%}\n\n"
115
- summary += "This appears to be a background sequence.\n\n"
116
-
117
- summary += f"---\n**Processing Info:**\n"
118
- summary += f"- Images analyzed: {len(images)}\n"
119
- summary += f"- Model: EfficientNet-B0\n"
120
- summary += f"- Accuracy: 97.7%"
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
  return fig, summary
123
 
124
  except Exception as e:
125
- return None, f"❌ Error: {str(e)}"
126
 
127
  detector = CometDetectorV3('best_model.pth')
128
 
129
- with gr.Blocks(theme=gr.themes.Soft(), title="SOHO Comet Detector") as demo:
130
- gr.Markdown("""
131
- # 🌟 AI-Powered SOHO Comet Detector
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
- **Upload a ZIP file** containing SOHO/LASCO C3 FITS images from a time sequence.
134
- The AI will classify whether the sequence contains comet activity.
 
 
 
 
 
 
135
 
136
- ### πŸ“‹ Instructions:
137
- 1. Download SOHO LASCO C3 images (6-hour sequence recommended)
138
- 2. Put all .fts or .fits files in a folder
139
- 3. Zip the folder and upload here
140
- 4. Click "Analyze Sequence"
141
 
142
- ### πŸ”¬ Model Details:
143
- - **Architecture:** EfficientNet-B0
144
- - **Method:** Difference imaging + full-image classification
145
- - **Accuracy:** 97.7% on validation data
146
- - **Precision:** 98% (comet detection)
147
- - **Recall:** 99% (comet detection)
148
 
149
  ---
150
  """)
151
 
152
  with gr.Row():
153
- with gr.Column():
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  zip_input = gr.File(
155
- label="Upload ZIP of FITS Images",
156
  file_types=[".zip"],
157
- type="filepath"
 
158
  )
159
- analyze_btn = gr.Button("πŸ” Analyze Sequence", variant="primary", size="lg")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
- with gr.Column():
162
- output_plot = gr.Plot(label="Analysis Results")
163
- output_text = gr.Markdown(label="Detection Summary")
 
 
164
 
165
  gr.Markdown("""
166
  ---
167
- ### πŸ“Š About This System
168
 
169
- This system uses difference imaging to highlight moving objects (comets) in SOHO coronagraph data,
170
- then classifies the entire sequence using a convolutional neural network.
 
 
171
 
172
- **Training Data:** 498 comet sequences + 167 background sequences from SOHO/LASCO C3
173
 
174
- **Team:** Sambhavi, Emily, Mohammed
175
 
176
- *Built with Gradio β€’ Powered by Hugging Face*
 
 
177
  """)
178
 
179
  analyze_btn.click(
@@ -183,4 +310,8 @@ with gr.Blocks(theme=gr.themes.Soft(), title="SOHO Comet Detector") as demo:
183
  )
184
 
185
  if __name__ == "__main__":
186
- demo.launch()
 
 
 
 
 
33
 
34
  fits_files = sorted(Path(tmpdir).rglob('*.fts')) + sorted(Path(tmpdir).rglob('*.fits'))
35
 
36
+ for fpath in fits_files[:50]: # Limit to 50 files to prevent timeout
37
  try:
38
  with fits.open(fpath) as hdul:
39
  img = hdul[0].data.astype(np.float32)
 
56
  return max_proj
57
 
58
  def classify_image(self, max_proj):
 
59
  img = (max_proj - max_proj.min()) / (max_proj.max() - max_proj.min() + 1e-8)
 
 
60
  img = cv2.resize(img, (512, 512))
 
 
61
  img_rgb = np.stack([img, img, img], axis=0)
62
  img_tensor = torch.FloatTensor(img_rgb).unsqueeze(0).to(self.device)
 
 
63
  img_tensor = self.transform(img_tensor)
64
 
 
65
  with torch.no_grad():
66
  output = self.model(img_tensor)
67
  probs = torch.softmax(output, dim=1)
 
72
 
73
  def process_and_visualize(self, zip_file):
74
  try:
75
+ if zip_file is None:
76
+ return None, "⚠️ Please upload a ZIP file"
77
+
78
  images = self.load_fits_from_zip(zip_file.name)
79
 
80
  if len(images) < 2:
81
+ return None, "❌ Need at least 2 FITS images in the ZIP file"
82
 
83
  max_proj = self.create_difference_images(images)
84
  pred_class, confidence = self.classify_image(max_proj)
85
 
86
+ # Create figure with dark background
87
+ plt.style.use('dark_background')
88
+ fig, axes = plt.subplots(1, 2, figsize=(16, 7))
89
+ fig.patch.set_facecolor('#0B1120')
90
 
91
+ # First image
92
  axes[0].imshow(images[0], cmap='gray')
93
+ axes[0].set_title('Original SOHO/LASCO C3 Image',
94
+ fontsize=13, color='#E0E0E0', pad=15)
95
  axes[0].axis('off')
96
 
97
+ # Difference projection
98
  axes[1].imshow(max_proj, cmap='hot')
99
  if pred_class == 1:
100
+ axes[1].set_title('🌟 COMET SIGNATURE DETECTED',
101
+ fontsize=14, color='#00FF88', weight='bold', pad=15)
102
  else:
103
+ axes[1].set_title('Background Sequence',
104
+ fontsize=13, color='#FFB366', pad=15)
105
  axes[1].axis('off')
106
 
107
  plt.tight_layout()
108
 
109
+ # Summary with enhanced styling
110
  if pred_class == 1:
111
+ summary = f"""
112
+ # 🌟 COMET DETECTED!
113
+
114
+ ### Detection Confidence: {confidence:.1%}
115
+
116
+ ---
117
+
118
+ **Analysis Results:**
119
+ - **Classification:** Comet Event βœ…
120
+ - **Confidence Score:** {confidence:.3f}
121
+ - **Images Analyzed:** {len(images)}
122
+ - **Detection Method:** Difference Imaging + CNN
123
+
124
+ **Interpretation:**
125
+ This sequence shows characteristic signatures of a sungrazing comet passing through
126
+ the SOHO/LASCO C3 field of view. The bright trail in the difference projection
127
+ indicates significant motion and brightness changes consistent with comet activity.
128
+
129
+ ---
130
+ *Model: EfficientNet-B0 | Accuracy: 97.7%*
131
+ """
132
  else:
133
+ summary = f"""
134
+ # πŸŒ‘ No Comet Detected
135
+
136
+ ### Background Confidence: {confidence:.1%}
137
+
138
+ ---
139
+
140
+ **Analysis Results:**
141
+ - **Classification:** Background Sequence βšͺ
142
+ - **Confidence Score:** {confidence:.3f}
143
+ - **Images Analyzed:** {len(images)}
144
+ - **Detection Method:** Difference Imaging + CNN
145
+
146
+ **Interpretation:**
147
+ This sequence does not show signatures consistent with comet activity.
148
+ The difference projection reveals minimal motion or brightness changes,
149
+ typical of background coronagraph observations.
150
+
151
+ ---
152
+ *Model: EfficientNet-B0 | Accuracy: 97.7%*
153
+ """
154
 
155
  return fig, summary
156
 
157
  except Exception as e:
158
+ return None, f"❌ **Processing Error**\n\n{str(e)}\n\nPlease ensure your ZIP contains valid SOHO FITS files."
159
 
160
  detector = CometDetectorV3('best_model.pth')
161
 
162
+ # Custom CSS for astronomy theme
163
+ custom_css = """
164
+ @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;600;700&display=swap');
165
+
166
+ body {
167
+ font-family: 'Space Grotesk', sans-serif !important;
168
+ }
169
+
170
+ .gradio-container {
171
+ background: linear-gradient(135deg, #0B1120 0%, #1a1f35 100%) !important;
172
+ }
173
+
174
+ .contain {
175
+ background: rgba(15, 20, 35, 0.8) !important;
176
+ backdrop-filter: blur(10px) !important;
177
+ border: 1px solid rgba(255, 255, 255, 0.1) !important;
178
+ border-radius: 16px !important;
179
+ }
180
+
181
+ h1 {
182
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
183
+ -webkit-background-clip: text;
184
+ -webkit-text-fill-color: transparent;
185
+ font-weight: 700 !important;
186
+ font-size: 3em !important;
187
+ text-align: center !important;
188
+ margin-bottom: 1em !important;
189
+ }
190
+
191
+ .gr-button-primary {
192
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
193
+ border: none !important;
194
+ font-weight: 600 !important;
195
+ font-size: 1.1em !important;
196
+ padding: 12px 24px !important;
197
+ transition: all 0.3s ease !important;
198
+ }
199
+
200
+ .gr-button-primary:hover {
201
+ transform: translateY(-2px) !important;
202
+ box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4) !important;
203
+ }
204
+
205
+ .markdown-text {
206
+ color: #E0E0E0 !important;
207
+ }
208
+
209
+ .gr-box {
210
+ border-radius: 12px !important;
211
+ border: 1px solid rgba(255, 255, 255, 0.1) !important;
212
+ }
213
+
214
+ footer {
215
+ display: none !important;
216
+ }
217
+ """
218
+
219
+ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css, title="SOHO Comet Detector") as demo:
220
 
221
+ gr.HTML("""
222
+ <div style="text-align: center; margin-bottom: 2em;">
223
+ <h1>🌌 SOHO Comet Detection System</h1>
224
+ <p style="font-size: 1.2em; color: #B0B0B0; font-weight: 300;">
225
+ AI-Powered Analysis of NASA Solar Coronagraph Data
226
+ </p>
227
+ </div>
228
+ """)
229
 
230
+ gr.Markdown("""
231
+ ### πŸ›Έ About This System
232
+
233
+ This deep learning system automatically detects sungrazing comets in SOHO/LASCO C3
234
+ coronagraph images using difference imaging and convolutional neural networks.
235
 
236
+ **Model Performance:**
237
+ - ✨ **97.7% Accuracy** on validation data
238
+ - 🎯 **98% Precision** for comet detection
239
+ - πŸ” **99% Recall** for comet detection
 
 
240
 
241
  ---
242
  """)
243
 
244
  with gr.Row():
245
+ with gr.Column(scale=1):
246
+ gr.Markdown("""
247
+ ### πŸ“€ Upload Data
248
+
249
+ **Instructions:**
250
+ 1. Download SOHO LASCO C3 FITS images (6-hour time sequence recommended)
251
+ 2. Place all `.fts` or `.fits` files in a folder
252
+ 3. Create a ZIP archive of the folder
253
+ 4. Upload the ZIP file below
254
+ 5. Click "Analyze Sequence"
255
+
256
+ **Maximum:** 50 images per upload
257
+ """)
258
+
259
  zip_input = gr.File(
260
+ label="πŸ“ Upload ZIP File",
261
  file_types=[".zip"],
262
+ type="filepath",
263
+ file_count="single"
264
  )
265
+
266
+ analyze_btn = gr.Button(
267
+ "πŸ” Analyze Sequence",
268
+ variant="primary",
269
+ size="lg"
270
+ )
271
+
272
+ gr.Markdown("""
273
+ ---
274
+
275
+ ### πŸ”¬ Technical Details
276
+
277
+ **Architecture:** EfficientNet-B0
278
+ **Input Size:** 512Γ—512 px
279
+ **Method:** Maximum difference projection + binary classification
280
+ **Training Data:** 498 comet + 167 background sequences
281
+ """)
282
 
283
+ with gr.Column(scale=2):
284
+ gr.Markdown("### πŸ“Š Analysis Results")
285
+
286
+ output_plot = gr.Plot(label="Visual Analysis")
287
+ output_text = gr.Markdown(label="Detection Report")
288
 
289
  gr.Markdown("""
290
  ---
 
291
 
292
+ ### πŸ“š Data Source
293
+
294
+ Training data sourced from the [NASA SOHO mission](https://soho.nascom.nasa.gov/)
295
+ LASCO C3 coronagraph and the [Sungrazer Project](https://sungrazer.nrl.navy.mil/).
296
 
297
+ ### πŸ‘₯ Development Team
298
 
299
+ **Sambhavi** β€’ **Emily** β€’ **Mohammed**
300
 
301
+ ---
302
+
303
+ *Built with Gradio β€’ Powered by Hugging Face Spaces β€’ 2025*
304
  """)
305
 
306
  analyze_btn.click(
 
310
  )
311
 
312
  if __name__ == "__main__":
313
+ demo.launch(
314
+ server_name="0.0.0.0",
315
+ server_port=7860,
316
+ show_error=True
317
+ )