-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepomix-output.xml
More file actions
5986 lines (5258 loc) · 193 KB
/
repomix-output.xml
File metadata and controls
5986 lines (5258 loc) · 193 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
This file is a merged representation of the entire codebase, combined into a single document by Repomix.
<file_summary>
This section contains a summary of this file.
<purpose>
This file contains a packed representation of the entire repository's contents.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>
<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
- File path as an attribute
- Full contents of the file
</file_format>
<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
- When processing this file, use the file path to distinguish
between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
</usage_guidelines>
<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>
</file_summary>
<directory_structure>
.emergent/emergent.yml
backend/.env
backend/requirements.txt
backend/server.py
frontend/.env
frontend/.gitignore
frontend/components.json
frontend/craco.config.js
frontend/jsconfig.json
frontend/package.json
frontend/postcss.config.js
frontend/public/index.html
frontend/README.md
frontend/src/App.css
frontend/src/App.js
frontend/src/components/ui/accordion.jsx
frontend/src/components/ui/alert-dialog.jsx
frontend/src/components/ui/alert.jsx
frontend/src/components/ui/aspect-ratio.jsx
frontend/src/components/ui/avatar.jsx
frontend/src/components/ui/badge.jsx
frontend/src/components/ui/breadcrumb.jsx
frontend/src/components/ui/button.jsx
frontend/src/components/ui/calendar.jsx
frontend/src/components/ui/card.jsx
frontend/src/components/ui/carousel.jsx
frontend/src/components/ui/checkbox.jsx
frontend/src/components/ui/collapsible.jsx
frontend/src/components/ui/command.jsx
frontend/src/components/ui/context-menu.jsx
frontend/src/components/ui/dialog.jsx
frontend/src/components/ui/drawer.jsx
frontend/src/components/ui/dropdown-menu.jsx
frontend/src/components/ui/form.jsx
frontend/src/components/ui/hover-card.jsx
frontend/src/components/ui/input-otp.jsx
frontend/src/components/ui/input.jsx
frontend/src/components/ui/label.jsx
frontend/src/components/ui/menubar.jsx
frontend/src/components/ui/navigation-menu.jsx
frontend/src/components/ui/pagination.jsx
frontend/src/components/ui/popover.jsx
frontend/src/components/ui/progress.jsx
frontend/src/components/ui/radio-group.jsx
frontend/src/components/ui/resizable.jsx
frontend/src/components/ui/scroll-area.jsx
frontend/src/components/ui/select.jsx
frontend/src/components/ui/separator.jsx
frontend/src/components/ui/sheet.jsx
frontend/src/components/ui/skeleton.jsx
frontend/src/components/ui/slider.jsx
frontend/src/components/ui/sonner.jsx
frontend/src/components/ui/switch.jsx
frontend/src/components/ui/table.jsx
frontend/src/components/ui/tabs.jsx
frontend/src/components/ui/textarea.jsx
frontend/src/components/ui/toast.jsx
frontend/src/components/ui/toaster.jsx
frontend/src/components/ui/toggle-group.jsx
frontend/src/components/ui/toggle.jsx
frontend/src/components/ui/tooltip.jsx
frontend/src/hooks/use-toast.js
frontend/src/index.css
frontend/src/index.js
frontend/src/lib/utils.js
frontend/tailwind.config.js
gitignore.txt
README.md
test_result.md
</directory_structure>
<files>
This section contains the contents of the repository's files.
<file path=".emergent/emergent.yml">
{
"env_image_name": "fastapi_react_mongo_shadcn_base_image_cloud_arm:release-26092025-2"
}
</file>
<file path="backend/.env">
MONGO_URL="mongodb://localhost:27017"
DB_NAME="test_database"
CORS_ORIGINS="*"
</file>
<file path="backend/requirements.txt">
annotated-types==0.7.0
anyio==4.11.0
black==25.9.0
boto3==1.40.39
botocore==1.40.39
certifi==2025.8.3
cffi==2.0.0
charset-normalizer==3.4.3
click==8.3.0
cryptography==46.0.1
dnspython==2.8.0
ecdsa==0.19.1
email-validator==2.3.0
fastapi==0.110.1
flake8==7.3.0
h11==0.16.0
httpcore==1.0.9
httpx==0.28.1
idna==3.10
iniconfig==2.1.0
isort==6.0.1
jmespath==1.0.1
jq==1.10.0
markdown-it-py==4.0.0
mccabe==0.7.0
mdurl==0.1.2
motor==3.3.1
mypy==1.18.2
mypy_extensions==1.1.0
numpy==2.3.3
oauthlib==3.3.1
packaging==25.0
pandas==2.3.2
passlib==1.7.4
pathspec==0.12.1
platformdirs==4.4.0
pluggy==1.6.0
pyasn1==0.6.1
pycodestyle==2.14.0
pycparser==2.23
pydantic==2.11.9
pydantic_core==2.33.2
pyflakes==3.4.0
Pygments==2.19.2
PyJWT==2.10.1
pymongo==4.5.0
pytest==8.4.2
python-dateutil==2.9.0.post0
python-dotenv==1.1.1
python-jose==3.5.0
python-multipart==0.0.20
pytokens==0.1.10
pytz==2025.2
requests==2.32.5
requests-oauthlib==2.0.0
rich==14.1.0
rsa==4.9.1
s3transfer==0.14.0
s5cmd==0.2.0
shellingham==1.5.4
six==1.17.0
sniffio==1.3.1
starlette==0.37.2
typer==0.19.2
typing-inspection==0.4.1
typing_extensions==4.15.0
tzdata==2025.2
urllib3==2.5.0
uvicorn==0.25.0
watchfiles==1.1.0
</file>
<file path="backend/server.py">
from fastapi import FastAPI, APIRouter, HTTPException, Query, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from motor.motor_asyncio import AsyncIOMotorClient
from dotenv import load_dotenv
from pathlib import Path
import os
import logging
from pydantic import BaseModel, Field
from typing import List, Dict, Any, Optional
from datetime import datetime, date, timedelta
import httpx
import asyncio
from contextlib import asynccontextmanager
import uuid
ROOT_DIR = Path(__file__).parent
load_dotenv(ROOT_DIR / '.env')
# MongoDB connection
mongo_url = os.environ['MONGO_URL']
client = AsyncIOMotorClient(mongo_url)
db = client[os.environ['DB_NAME']]
# NASA API configuration
NASA_API_KEY = "DEMO_KEY" # Using demo key for initial development
NASA_BASE_URL = "https://api.nasa.gov/neo/rest/v1"
# Global HTTP client
http_client: Optional[httpx.AsyncClient] = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global http_client
# Initialize HTTP client
http_client = httpx.AsyncClient(timeout=30.0)
logging.info("NASA API client initialized")
yield
# Cleanup
if http_client:
await http_client.aclose()
logging.info("NASA API client closed")
# Create FastAPI app
app = FastAPI(
title="Meteor Madness - Asteroid Impact Portal",
description="Advanced asteroid visualization and mitigation platform",
version="1.0.0",
lifespan=lifespan
)
# Create API router
api_router = APIRouter(prefix="/api")
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_credentials=True,
allow_origins=os.environ.get('CORS_ORIGINS', '*').split(','),
allow_methods=["*"],
allow_headers=["*"],
)
# Pydantic models
class AsteroidSummary(BaseModel):
id: str
name: str
diameter_km: Optional[float] = None
velocity_kmh: Optional[float] = None
miss_distance_km: Optional[float] = None
is_hazardous: bool = False
approach_date: Optional[str] = None
class AsteroidDetails(BaseModel):
id: str
name: str
nasa_jpl_url: str
absolute_magnitude: Optional[float] = None
diameter_min_km: Optional[float] = None
diameter_max_km: Optional[float] = None
is_hazardous: bool = False
orbital_data: Optional[Dict[str, Any]] = None
close_approaches: List[Dict[str, Any]] = []
class SimulationInput(BaseModel):
diameter_km: float = Field(..., ge=0.001, le=100, description="Asteroid diameter in kilometers")
velocity_kms: float = Field(..., ge=1, le=100, description="Impact velocity in km/s")
angle_degrees: float = Field(45, ge=10, le=90, description="Impact angle in degrees")
composition: str = Field("rocky", description="Asteroid composition")
target_location: str = Field("land", description="Impact location type")
class SimulationResult(BaseModel):
crater_diameter_km: float
energy_megatons: float
affected_radius_km: float
population_at_risk: int
damage_assessment: Dict[str, str]
seismic_magnitude: float
fireball_radius_km: float
class MitigationStrategy(BaseModel):
id: str
name: str
description: str
effectiveness_percent: float
cost_billions_usd: float
timeline_years: float
technology_readiness: int
pros: List[str]
cons: List[str]
# NASA API helper functions
async def fetch_nasa_data(endpoint: str, params: Dict[str, Any] = None) -> Dict[str, Any]:
"""Fetch data from NASA NeoWs API"""
global http_client
if not http_client:
raise HTTPException(status_code=503, detail="HTTP client not available")
url = f"{NASA_BASE_URL}{endpoint}"
params = params or {}
params["api_key"] = NASA_API_KEY
try:
response = await http_client.get(url, params=params)
response.raise_for_status()
return response.json()
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
raise HTTPException(status_code=404, detail="Asteroid not found")
elif e.response.status_code == 429:
raise HTTPException(status_code=429, detail="NASA API rate limit exceeded")
else:
raise HTTPException(status_code=503, detail=f"NASA API error: {e.response.status_code}")
except Exception as e:
logging.error(f"NASA API request failed: {e}")
raise HTTPException(status_code=503, detail="NASA API service unavailable")
def parse_asteroid_summary(asteroid_data: Dict[str, Any]) -> AsteroidSummary:
"""Parse NASA asteroid data into summary format"""
close_approaches = asteroid_data.get("close_approach_data", [])
closest_approach = min(close_approaches, key=lambda x: float(x["miss_distance"]["kilometers"])) if close_approaches else None
diameter_data = asteroid_data.get("estimated_diameter", {}).get("kilometers", {})
diameter_km = diameter_data.get("estimated_diameter_max") if diameter_data else None
velocity_kmh = None
miss_distance_km = None
approach_date = None
if closest_approach:
velocity_kmh = float(closest_approach["relative_velocity"]["kilometers_per_hour"])
miss_distance_km = float(closest_approach["miss_distance"]["kilometers"])
approach_date = closest_approach["close_approach_date"]
return AsteroidSummary(
id=asteroid_data["id"],
name=asteroid_data["name"],
diameter_km=diameter_km,
velocity_kmh=velocity_kmh,
miss_distance_km=miss_distance_km,
is_hazardous=asteroid_data["is_potentially_hazardous_asteroid"],
approach_date=approach_date
)
def calculate_impact_simulation(params: SimulationInput) -> SimulationResult:
"""Calculate asteroid impact simulation results"""
import math
# Basic impact physics calculations
diameter_m = params.diameter_km * 1000
velocity_ms = params.velocity_kms * 1000
# Asteroid mass estimation (assuming rocky composition, density ~2600 kg/m³)
radius_m = diameter_m / 2
volume_m3 = (4/3) * math.pi * (radius_m ** 3)
mass_kg = volume_m3 * 2600 # Rocky asteroid density
# Kinetic energy calculation
energy_joules = 0.5 * mass_kg * (velocity_ms ** 2)
energy_megatons = energy_joules / (4.184e15) # Convert to megatons TNT
# Crater diameter (complex crater scaling)
crater_diameter_km = 1.8 * (params.diameter_km ** 0.13) * (params.velocity_kms ** 0.44) * (math.sin(math.radians(params.angle_degrees)) ** 0.33)
# Affected radius (various damage zones)
fireball_radius_km = 0.028 * (energy_megatons ** 0.33)
blast_radius_km = 0.4 * (energy_megatons ** 0.33)
thermal_radius_km = 1.9 * (energy_megatons ** 0.33)
affected_radius_km = max(fireball_radius_km, blast_radius_km, thermal_radius_km)
# Population estimation (rough global average)
affected_area_km2 = math.pi * (affected_radius_km ** 2)
population_density_per_km2 = 15 # Global average
population_at_risk = int(affected_area_km2 * population_density_per_km2)
# Seismic magnitude estimation
seismic_magnitude = 0.67 * math.log10(energy_megatons) + 5.87
# Damage assessment
if energy_megatons < 1:
damage_level = "Local damage, buildings destroyed within blast radius"
elif energy_megatons < 100:
damage_level = "Regional catastrophe, severe damage across metropolitan area"
elif energy_megatons < 10000:
damage_level = "National disaster, continent-wide effects"
else:
damage_level = "Global catastrophe, mass extinction event"
damage_assessment = {
"overall": damage_level,
"crater": f"Crater diameter: {crater_diameter_km:.1f} km",
"fireball": f"Fireball radius: {fireball_radius_km:.1f} km",
"blast": f"Blast damage radius: {blast_radius_km:.1f} km",
"thermal": f"Thermal radiation radius: {thermal_radius_km:.1f} km"
}
return SimulationResult(
crater_diameter_km=crater_diameter_km,
energy_megatons=energy_megatons,
affected_radius_km=affected_radius_km,
population_at_risk=population_at_risk,
damage_assessment=damage_assessment,
seismic_magnitude=seismic_magnitude,
fireball_radius_km=fireball_radius_km
)
# API Routes
@api_router.get("/")
async def root():
return {"message": "Meteor Madness - Asteroid Impact Portal API", "version": "1.0.0"}
@api_router.get("/asteroids/feed", response_model=List[AsteroidSummary])
async def get_asteroid_feed(
start_date: date = Query(..., description="Start date (YYYY-MM-DD)"),
end_date: Optional[date] = Query(None, description="End date (YYYY-MM-DD)")
):
"""Get asteroid feed from NASA for specified date range"""
if end_date is None:
end_date = start_date
# NASA API limits to 7 days
if (end_date - start_date).days > 7:
raise HTTPException(status_code=400, detail="Date range cannot exceed 7 days")
params = {
"start_date": start_date.isoformat(),
"end_date": end_date.isoformat()
}
data = await fetch_nasa_data("/feed", params)
asteroids = []
for date_key, daily_asteroids in data.get("near_earth_objects", {}).items():
for asteroid in daily_asteroids:
try:
asteroids.append(parse_asteroid_summary(asteroid))
except Exception as e:
logging.warning(f"Failed to parse asteroid {asteroid.get('id', 'unknown')}: {e}")
continue
# Sort by closest approach distance
asteroids.sort(key=lambda x: x.miss_distance_km or float('inf'))
return asteroids
@api_router.get("/asteroids/{asteroid_id}", response_model=AsteroidDetails)
async def get_asteroid_details(asteroid_id: str):
"""Get detailed information about a specific asteroid"""
data = await fetch_nasa_data(f"/neo/{asteroid_id}")
diameter_data = data.get("estimated_diameter", {}).get("kilometers", {})
return AsteroidDetails(
id=data["id"],
name=data["name"],
nasa_jpl_url=data["nasa_jpl_url"],
absolute_magnitude=data.get("absolute_magnitude_h"),
diameter_min_km=diameter_data.get("estimated_diameter_min"),
diameter_max_km=diameter_data.get("estimated_diameter_max"),
is_hazardous=data["is_potentially_hazardous_asteroid"],
orbital_data=data.get("orbital_data"),
close_approaches=data.get("close_approach_data", [])
)
@api_router.get("/asteroids/browse", response_model=List[AsteroidSummary])
async def browse_asteroids(
page: int = Query(0, ge=0, description="Page number"),
size: int = Query(20, ge=1, le=50, description="Page size")
):
"""Browse asteroids with pagination"""
params = {"page": page, "size": size}
data = await fetch_nasa_data("/neo/browse", params)
asteroids = []
for asteroid in data.get("near_earth_objects", []):
try:
asteroids.append(parse_asteroid_summary(asteroid))
except Exception as e:
logging.warning(f"Failed to parse asteroid {asteroid.get('id', 'unknown')}: {e}")
continue
return asteroids
@api_router.get("/asteroids/hazardous", response_model=List[AsteroidSummary])
async def get_hazardous_asteroids():
"""Get potentially hazardous asteroids from recent data"""
# Get data for the last 7 days
end_date = date.today()
start_date = end_date - timedelta(days=7)
params = {
"start_date": start_date.isoformat(),
"end_date": end_date.isoformat()
}
data = await fetch_nasa_data("/feed", params)
hazardous_asteroids = []
for date_key, daily_asteroids in data.get("near_earth_objects", {}).items():
for asteroid in daily_asteroids:
if asteroid["is_potentially_hazardous_asteroid"]:
try:
hazardous_asteroids.append(parse_asteroid_summary(asteroid))
except Exception as e:
logging.warning(f"Failed to parse hazardous asteroid {asteroid.get('id', 'unknown')}: {e}")
continue
# Sort by size (largest first)
hazardous_asteroids.sort(key=lambda x: x.diameter_km or 0, reverse=True)
return hazardous_asteroids
@api_router.post("/simulation/impact", response_model=SimulationResult)
async def simulate_impact(params: SimulationInput):
"""Simulate asteroid impact with given parameters"""
return calculate_impact_simulation(params)
@api_router.get("/mitigation/strategies", response_model=List[MitigationStrategy])
async def get_mitigation_strategies():
"""Get available asteroid mitigation strategies"""
strategies = [
MitigationStrategy(
id="kinetic_impactor",
name="Kinetic Impactor",
description="Spacecraft collision to change asteroid trajectory",
effectiveness_percent=75,
cost_billions_usd=2.5,
timeline_years=5,
technology_readiness=8,
pros=["Proven technology", "Relatively low cost", "Quick deployment"],
cons=["Limited to smaller asteroids", "Requires early detection", "Single point of failure"]
),
MitigationStrategy(
id="gravity_tractor",
name="Gravity Tractor",
description="Spacecraft uses gravitational force to gradually change orbit",
effectiveness_percent=60,
cost_billions_usd=5.0,
timeline_years=10,
technology_readiness=6,
pros=["Very precise control", "No debris creation", "Scalable force"],
cons=["Very slow process", "High cost", "Requires decades of warning"]
),
MitigationStrategy(
id="nuclear_deflection",
name="Nuclear Deflection",
description="Nuclear device detonation to change asteroid trajectory",
effectiveness_percent=95,
cost_billions_usd=15.0,
timeline_years=3,
technology_readiness=7,
pros=["Very effective", "Works on large asteroids", "Proven nuclear technology"],
cons=["Political challenges", "Risk of fragmentation", "Complex mission"]
),
MitigationStrategy(
id="ion_beam",
name="Ion Beam Shepherd",
description="Ion propulsion to slowly deflect asteroid over time",
effectiveness_percent=70,
cost_billions_usd=8.0,
timeline_years=15,
technology_readiness=5,
pros=["Precise control", "No contamination", "Continuous operation"],
cons=["Requires very early detection", "Complex technology", "Long deployment time"]
),
MitigationStrategy(
id="solar_sail",
name="Solar Sail/Mirror",
description="Reflective material to create radiation pressure",
effectiveness_percent=40,
cost_billions_usd=3.0,
timeline_years=20,
technology_readiness=4,
pros=["No fuel required", "Sustainable operation", "Minimal mass needed"],
cons=["Very slow process", "Limited effectiveness", "Deployment challenges"]
)
]
return strategies
@api_router.get("/statistics/dashboard")
async def get_dashboard_statistics():
"""Get comprehensive statistics for dashboard"""
try:
# Get recent asteroid data
end_date = date.today()
start_date = end_date - timedelta(days=7)
params = {
"start_date": start_date.isoformat(),
"end_date": end_date.isoformat()
}
data = await fetch_nasa_data("/feed", params)
total_asteroids = 0
hazardous_count = 0
size_categories = {"small": 0, "medium": 0, "large": 0, "unknown": 0}
closest_approach = {"distance": float('inf'), "name": "", "date": ""}
for date_key, daily_asteroids in data.get("near_earth_objects", {}).items():
total_asteroids += len(daily_asteroids)
for asteroid in daily_asteroids:
if asteroid["is_potentially_hazardous_asteroid"]:
hazardous_count += 1
# Size categorization
diameter_data = asteroid.get("estimated_diameter", {}).get("kilometers", {})
if diameter_data:
max_diameter = diameter_data.get("estimated_diameter_max", 0)
if max_diameter < 0.1:
size_categories["small"] += 1
elif max_diameter < 1.0:
size_categories["medium"] += 1
else:
size_categories["large"] += 1
else:
size_categories["unknown"] += 1
# Find closest approach
for approach in asteroid.get("close_approach_data", []):
distance_km = float(approach["miss_distance"]["kilometers"])
if distance_km < closest_approach["distance"]:
closest_approach = {
"distance": distance_km,
"name": asteroid["name"],
"date": approach["close_approach_date"]
}
return {
"total_asteroids": total_asteroids,
"hazardous_asteroids": hazardous_count,
"hazardous_percentage": (hazardous_count / total_asteroids * 100) if total_asteroids > 0 else 0,
"size_distribution": size_categories,
"closest_approach": closest_approach,
"observation_period": f"{start_date} to {end_date}"
}
except Exception as e:
logging.error(f"Failed to get dashboard statistics: {e}")
return {
"total_asteroids": 0,
"hazardous_asteroids": 0,
"hazardous_percentage": 0,
"size_distribution": {"small": 0, "medium": 0, "large": 0, "unknown": 0},
"closest_approach": {"distance": 0, "name": "N/A", "date": ""},
"observation_period": "No data available"
}
# Include router
app.include_router(api_router)
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
@asynccontextmanager
async def lifespan(app: FastAPI):
global http_client
# Startup
http_client = httpx.AsyncClient(timeout=30.0)
logging.info("NASA API client initialized")
yield # 👈 yaha tak startup chalega, uske baad app request serve karega
# Shutdown
if http_client:
await http_client.aclose()
logging.info("NASA API client closed")
client.close()
logging.info("MongoDB client closed")
#@app.on_event("shutdown")
#async def shutdown_db_client():
# client.close()
</file>
<file path="frontend/.env">
REACT_APP_BACKEND_URL=https://asteroid-alert.preview.emergentagent.com
WDS_SOCKET_PORT=443
</file>
<file path="frontend/.gitignore">
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
</file>
<file path="frontend/components.json">
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": false,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
</file>
<file path="frontend/craco.config.js">
// Load configuration from environment or config file
const path = require('path');
// Environment variable overrides
const config = {
disableHotReload: process.env.DISABLE_HOT_RELOAD === 'true',
};
module.exports = {
webpack: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
configure: (webpackConfig) => {
// Disable hot reload completely if environment variable is set
if (config.disableHotReload) {
// Remove hot reload related plugins
webpackConfig.plugins = webpackConfig.plugins.filter(plugin => {
return !(plugin.constructor.name === 'HotModuleReplacementPlugin');
});
// Disable watch mode
webpackConfig.watch = false;
webpackConfig.watchOptions = {
ignored: /.*/, // Ignore all files
};
} else {
// Add ignored patterns to reduce watched directories
webpackConfig.watchOptions = {
...webpackConfig.watchOptions,
ignored: [
'**/node_modules/**',
'**/.git/**',
'**/build/**',
'**/dist/**',
'**/coverage/**',
'**/public/**',
],
};
}
return webpackConfig;
},
},
};
</file>
<file path="frontend/jsconfig.json">
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"]
}
</file>
<file path="frontend/package.json">
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@hookform/resolvers": "^5.0.1",
"@radix-ui/react-accordion": "^1.2.8",
"@radix-ui/react-alert-dialog": "^1.1.11",
"@radix-ui/react-aspect-ratio": "^1.1.4",
"@radix-ui/react-avatar": "^1.1.7",
"@radix-ui/react-checkbox": "^1.2.3",
"@radix-ui/react-collapsible": "^1.1.8",
"@radix-ui/react-context-menu": "^2.2.12",
"@radix-ui/react-dialog": "^1.1.11",
"@radix-ui/react-dropdown-menu": "^2.1.12",
"@radix-ui/react-hover-card": "^1.1.11",
"@radix-ui/react-label": "^2.1.4",
"@radix-ui/react-menubar": "^1.1.12",
"@radix-ui/react-navigation-menu": "^1.2.10",
"@radix-ui/react-popover": "^1.1.11",
"@radix-ui/react-progress": "^1.1.4",
"@radix-ui/react-radio-group": "^1.3.4",
"@radix-ui/react-scroll-area": "^1.2.6",
"@radix-ui/react-select": "^2.2.2",
"@radix-ui/react-separator": "^1.1.4",
"@radix-ui/react-slider": "^1.3.2",
"@radix-ui/react-slot": "^1.2.0",
"@radix-ui/react-switch": "^1.2.2",
"@radix-ui/react-tabs": "^1.1.9",
"@radix-ui/react-toast": "^1.2.11",
"@radix-ui/react-toggle": "^1.1.6",
"@radix-ui/react-toggle-group": "^1.1.7",
"@radix-ui/react-tooltip": "^1.2.4",
"axios": "^1.8.4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"cra-template": "1.2.0",
"date-fns": "^4.1.0",
"embla-carousel-react": "^8.6.0",
"input-otp": "^1.4.2",
"lucide-react": "^0.507.0",
"next-themes": "^0.4.6",
"react": "^19.0.0",
"react-day-picker": "8.10.1",
"react-dom": "^19.0.0",
"react-hook-form": "^7.56.2",
"react-resizable-panels": "^3.0.1",
"react-router-dom": "^7.5.1",
"react-scripts": "5.0.1",
"sonner": "^2.0.7",
"tailwind-merge": "^3.2.0",
"tailwindcss-animate": "^1.0.7",
"vaul": "^1.1.2",
"zod": "^3.24.4"
},
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@babel/plugin-proposal-private-property-in-object": "^7.21.11",
"@craco/craco": "^7.1.0",
"@eslint/js": "9.23.0",
"autoprefixer": "^10.4.20",
"eslint": "9.23.0",
"eslint-plugin-import": "2.31.0",
"eslint-plugin-jsx-a11y": "6.10.2",
"eslint-plugin-react": "7.37.4",
"globals": "15.15.0",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17"
},
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
}
</file>
<file path="frontend/postcss.config.js">
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
</file>
<file path="frontend/public/index.html">
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="A product of emergent.sh" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Emergent | Fullstack App</title>
<!--
These two scripts have been added for the testing, please do not edit or remove them
-->
<script src="https://unpkg.com/rrweb@latest/dist/rrweb.min.js"></script>
<script src="https://d2adkz2s9zrlge.cloudfront.net/rrweb-recorder-20250919-1.js"></script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<a
id="emergent-badge"
target="_blank"
href="https://app.emergent.sh/?utm_source=emergent-badge"
style="
display: flex !important;
align-items: center !important;
position: fixed !important;
bottom: 20px;
right: 20px;
text-decoration: none;
padding: 6px 10px;
font-family: -apple-system, BlinkMacSystemFont,
"Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell,
"Open Sans", "Helvetica Neue",
sans-serif !important;
font-size: 12px !important;
z-index: 9999 !important;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15) !important;
border-radius: 8px !important;
background-color: #ffffff !important;
border: 1px solid rgba(255, 255, 255, 0.25) !important;
"
>
<div
style="display: flex; flex-direction: row; align-items: center"
>
<img
style="width: 20px; height: 20px; margin-right: 8px"
src="https://avatars.githubusercontent.com/in/1201222?s=120&u=2686cf91179bbafbc7a71bfbc43004cf9ae1acea&v=4"
/>
<p
style="
color: #000000;
font-family: -apple-system, BlinkMacSystemFont,
"Segoe UI", Roboto, Oxygen, Ubuntu,
Cantarell, "Open Sans",
"Helvetica Neue", sans-serif !important;
font-size: 12px !important;
align-items: center;