cwadayi commited on
Commit
7b108b2
·
verified ·
1 Parent(s): 2329d9e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -3
app.py CHANGED
@@ -1,8 +1,96 @@
1
- from fastapi import FastAPI
 
 
 
 
2
 
3
- app = FastAPI()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  @app.get("/")
6
  def greet_json():
7
- return {"Hello": "World!"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from starlette.responses import JSONResponse
3
+ from obspy.clients.fdsn import Client
4
+ from obspy.core.utcdatetime import UTCDateTime
5
+ import logging
6
 
7
+ # Configure logging
8
+ logging.basicConfig(level=logging.INFO)
9
+
10
+ # Initialize the FastAPI app
11
+ app = FastAPI(
12
+ title="Earthquake Catalog API",
13
+ description="An API to fetch earthquake data from the IRIS FDSN web service, ready for Hugging Face.",
14
+ version="1.0.0",
15
+ )
16
+
17
+ # Initialize the IRIS FDSN client
18
+ # This is placed in a global scope to be reused across requests
19
+ try:
20
+ client = Client("IRIS")
21
+ logging.info("Successfully initialized IRIS FDSN client.")
22
+ except Exception as e:
23
+ client = None
24
+ logging.error(f"Could not initialize IRIS FDSN client on startup: {e}")
25
 
26
  @app.get("/")
27
  def greet_json():
28
+ """
29
+ A simple 'Hello World' endpoint.
30
+ """
31
+ return {"Hello": "World!", "message": "Go to /earthquakes to fetch data, or /docs for the API documentation."}
32
+
33
+ @app.get("/earthquakes")
34
+ async def get_earthquake_catalog():
35
+ """
36
+ Fetches earthquake data with a magnitude larger than 5.0
37
+ from 2015-01-05 to 2016-03-05.
38
+ """
39
+ if not client:
40
+ raise HTTPException(
41
+ status_code=503, # Service Unavailable
42
+ detail="The IRIS FDSN client is not available or failed to initialize.",
43
+ )
44
+
45
+ try:
46
+ # Define the query parameters
47
+ starttime = UTCDateTime("2015-01-05")
48
+ endtime = UTCDateTime("2016-03-05")
49
+ min_magnitude = 5.0
50
+
51
+ logging.info(f"Fetching events from {starttime} to {endtime} with min magnitude {min_magnitude}.")
52
+
53
+ # Fetch the earthquake catalog from the IRIS web service
54
+ catalog = client.get_events(
55
+ starttime=starttime,
56
+ endtime=endtime,
57
+ minmagnitude=min_magnitude,
58
+ )
59
+
60
+ logging.info(f"Found {len(catalog)} events.")
61
+
62
+ # Process the catalog into a more friendly JSON format
63
+ earthquake_list = []
64
+ for event in catalog:
65
+ # Ensure the event has a preferred origin and magnitude to avoid errors
66
+ if not event.preferred_origin() or not event.preferred_magnitude():
67
+ continue
68
+
69
+ origin = event.preferred_origin()
70
+ magnitude = event.preferred_magnitude()
71
+
72
+ # Extract place description
73
+ place = "N/A"
74
+ if event.descriptions:
75
+ place = event.descriptions[0].text
76
+
77
+ earthquake_list.append(
78
+ {
79
+ "time": origin.time.isoformat(),
80
+ "latitude": origin.latitude,
81
+ "longitude": origin.longitude,
82
+ "depth_km": origin.depth / 1000.0 if origin.depth is not None else None,
83
+ "magnitude": magnitude.mag,
84
+ "magnitude_type": magnitude.magnitude_type,
85
+ "place": place,
86
+ }
87
+ )
88
+
89
+ return JSONResponse(content={"earthquakes": earthquake_list})
90
 
91
+ except Exception as e:
92
+ logging.error(f"An error occurred while fetching data from IRIS FDSN: {e}")
93
+ raise HTTPException(
94
+ status_code=500, # Internal Server Error
95
+ detail=f"An internal error occurred while fetching data from the external service: {e}",
96
+ )