1- from fastapi import APIRouter , FastAPI , HTTPException , Response
21from pathlib import Path
32from time import perf_counter
4- import logging
53
6- from fastapi .responses import JSONResponse
4+ import geopandas as gpd
5+ import s3fs
6+ from fastapi import APIRouter , FastAPI , HTTPException , Response
77from fastapi .middleware .cors import CORSMiddleware
8-
8+ from fastapi . responses import JSONResponse
99from pydantic import BaseModel
10+ from shapely import GEOSException , convex_hull
11+ from shapely import wkt as shapely_wkt
12+ from shapely .geometry .base import BaseGeometry
13+
14+ from src import api_logger
1015from src .exceptions import MissingFrameException
1116from src .models import (
12- TimeSeriesModel ,
1317 GetFramesModel ,
18+ TimeSeriesModel ,
1419)
1520from src .timeseries import get_timeseries_over_aoi
16- from src import api_logger
17- import s3fs
18- import geopandas as gpd
1921
2022from . import log_router
21- from shapely import wkt as shapely_wkt
22- from shapely import convex_hull
23- from shapely .geometry .base import BaseGeometry
2423
2524router = APIRouter (route_class = log_router .LoggingRoute )
2625app = FastAPI ()
3938def read_root ():
4039 return {'Status' : 'A-Okay' }
4140
41+
4242class ReadLayer (BaseModel ):
4343 file_name : str
4444 layer : str
4545
46+
4647@app .post (
4748 '/timeseries' ,
4849 description = 'Returns a json response with values read at "unwrapped_phase", "interferometric_correlation", and "temporal_coherence" layers in provided files at given point' ,
4950)
5051def get_timeseries (series : TimeSeriesModel ):
51- # TODO: REMOVE BEFORE ANOTHER PRODUCTION RELEASE
52- return HTTPException (
53- status_code = 400 ,
54- detail = 'The test displacement API is temporarily disabled due to unintended usage. For programmatic queries please access the zarr stack store `displacement` layer directly. For more info or questions please contact uso@asf.alaska.edu' ,
55- )
52+ # # TODO: REMOVE BEFORE ANOTHER PRODUCTION RELEASE
53+ # return HTTPException(
54+ # status_code=400,
55+ # detail='The test displacement API is temporarily disabled due to unintended usage. For programmatic queries please access the zarr stack store `displacement` layer directly. For more info or questions please contact uso@asf.alaska.edu',
56+ # )
5657 start = perf_counter ()
5758 try :
5859 geometry = shapely_wkt .loads (series .wkt )
59- except BaseException as exc :
60+ except GEOSException as exc :
6061 raise HTTPException (
6162 400 , detail = f'Failed to load provided wkt string. Original Error: { exc } '
6263 )
6364 if geometry .geom_type not in ['Polygon' , 'Point' ]:
6465 raise HTTPException (
65- 400 , detail = f'Failed to load provided wkt. Must be "POLYGON" or "POINT", got { geometry .geom_type .upper ()} '
66+ 400 ,
67+ detail = f'Failed to load provided wkt. Must be "POLYGON" or "POINT", got { geometry .geom_type .upper ()} ' ,
6668 )
6769
6870 api_logger .debug (f'wkt loaded: { geometry .wkt } ' )
@@ -72,8 +74,8 @@ def get_timeseries(series: TimeSeriesModel):
7274 wkt = series .wkt ,
7375 frame_id = series .frameId ,
7476 polarization = series .polarization .value ,
75- flight_direction = series .flightDirection
76- )
77+ flight_direction = series .flightDirection ,
78+ )
7779
7880 api_logger .info (f'using file store: { file_store } ' )
7981
@@ -97,10 +99,14 @@ def get_timeseries(series: TimeSeriesModel):
9799)
98100def get_frame_ids (wkt_event : GetFramesModel ):
99101 return JSONResponse (
100- {'frame_ids' : sorted (_get_frames_for_wkt (wkt_event .wkt , wkt_event .flightDirection )), 'wkt' : wkt_event .wkt },
102+ {
103+ 'frame_ids' : sorted (_get_frames_for_wkt (wkt_event .wkt , wkt_event .flightDirection )),
104+ 'wkt' : wkt_event .wkt ,
105+ },
101106 headers = DEFAULT_HEADERS ,
102107 )
103108
109+
104110@app .post (
105111 '/frame_intersection' ,
106112 description = 'Returns the frame ids for a given aoi, splitting any cross frames' ,
@@ -112,40 +118,53 @@ def frame_intersection(wkt_event: GetFramesModel):
112118 frame_path = Path (__file__ ).parent .parent / 'data' / 'frames.geojson'
113119 geometry = shapely_wkt .loads (wkt_event .wkt )
114120 gdf = gpd .read_file (frame_path , engine = 'pyogrio' )
115- frames : gpd .GeoDataFrame = gdf [gdf ['frame_id' ].isin ([int (p ) for p in overlapping_frames ])] # type: ignore
121+ frames : gpd .GeoDataFrame = gdf [gdf ['frame_id' ].isin ([int (p ) for p in overlapping_frames ])]
116122 intersection = frames .intersection (geometry )
117123 return JSONResponse (
118- {_pad_frame_str (frame_id ): _simplify_multipolygons (geom ).wkt for frame_id , geom in zip (gdf .iloc [intersection .index ]['frame_id' ], intersection )},
124+ {
125+ _pad_frame_str (frame_id ): _simplify_multipolygons (geom ).wkt
126+ for frame_id , geom in zip (gdf .iloc [intersection .index ]['frame_id' ], intersection )
127+ },
119128 headers = DEFAULT_HEADERS ,
120129 )
121130
131+
122132def _simplify_multipolygons (geometry : BaseGeometry ) -> BaseGeometry :
123133 """In case polygon intersects different sections of frame at once and get multi-polygon (swath corners for example), perform convex hull instead"""
124134 if geometry .geom_type == 'MultiPolygon' :
125135 geometry = convex_hull (geometry )
126136
127137 return geometry
128138
139+
129140def _get_file_store_for_wkt (bucket : str , frame_id : str , polarization : str ):
130141 return f's3://{ bucket } /OPERA_L3_DISP-S1_STACK_V1/OPERA_L3_DISP-S1_IW_F{ frame_id } _{ polarization } _V1/OPERA_L3_DISP-S1_IW_F{ frame_id } _{ polarization } _short_wavelength_displacement.zarr.json.gz'
131142
132- def _get_zarr_store_uri (bucket : str , wkt : str , frame_id : str | None , polarization : str , flight_direction : str ):
143+
144+ def _get_zarr_store_uri (
145+ bucket : str , wkt : str , frame_id : str | None , polarization : str , flight_direction : str
146+ ):
133147 if isinstance (frame_id , str ):
134- zarr_store = _get_file_store_for_wkt (bucket = bucket , frame_id = frame_id , polarization = polarization )
148+ zarr_store = _get_file_store_for_wkt (
149+ bucket = bucket , frame_id = frame_id , polarization = polarization
150+ )
135151
136152 s3 = s3fs .S3FileSystem (anon = False )
137153 try :
138154 if s3 .exists (zarr_store ):
139155 return zarr_store
140156 except Exception as exc :
141- logging .debug (f'Failed to open store "{ zarr_store } ". Original exception: { exc } ' )
142- raise MissingFrameException (
143- 400 , f'No data found for the given area of interest { wkt } '
144- )
157+ api_logger .debug (f'Failed to open store "{ zarr_store } ". Original exception: { exc } ' )
158+ raise MissingFrameException (400 , f'No data found for the given area of interest { wkt } ' )
145159 else :
146- return _get_westmost_file_store_for_wkt (bucket = bucket , wkt = wkt , polarization = polarization , flight_direction = flight_direction )
160+ return _get_westmost_file_store_for_wkt (
161+ bucket = bucket , wkt = wkt , polarization = polarization , flight_direction = flight_direction
162+ )
147163
148- def _get_westmost_file_store_for_wkt (bucket : str , wkt : str , polarization : str , flight_direction : str ):
164+
165+ def _get_westmost_file_store_for_wkt (
166+ bucket : str , wkt : str , polarization : str , flight_direction : str
167+ ):
149168 # example:
150169 # s3://asf-cumulus-test-opera-products/OPERA_L3_DISP-S1_STACK_V1/OPERA_L3_DISP-S1_IW_F44328_VV_V1/OPERA_L3_DISP-S1_IW_F44328_VV_short_wavelength_displacement.zarr.json.gz
151170
@@ -162,21 +181,23 @@ def _get_westmost_file_store_for_wkt(bucket: str, wkt: str, polarization: str, f
162181 if s3 .exists (store ):
163182 available_zarr_stores .append (store )
164183 except Exception as exc :
165- logging .debug (f'Failed to open store "{ store } ". Original exception: { exc } ' )
184+ api_logger .debug (f'Failed to open store "{ store } ". Original exception: { exc } ' )
166185
167186 if len (available_zarr_stores ) == 0 :
168- raise MissingFrameException (
169- 400 , f'No data found for the given area of interest { wkt } '
170- )
187+ raise MissingFrameException (400 , f'No data found for the given area of interest { wkt } ' )
171188
172- return available_zarr_stores [0 ] if flight_direction .upper () == 'DESCENDING' else available_zarr_stores [- 1 ]
189+ return (
190+ available_zarr_stores [0 ]
191+ if flight_direction .upper () == 'DESCENDING'
192+ else available_zarr_stores [- 1 ]
193+ )
173194
174195
175196def _get_frames_for_wkt (wkt : str , flight_direction : str ) -> list [str ]:
176197 frame_path = Path (__file__ ).parent .parent / 'data' / 'frames.geojson'
177198 geometry = shapely_wkt .loads (wkt )
178199 gdf = gpd .read_file (frame_path , engine = 'pyogrio' )
179- result = gdf [gdf .orbit_direction == flight_direction ][gdf .intersects (geometry )]
200+ result = gdf [gdf .orbit_direction == flight_direction ][gdf .intersects (geometry )]
180201 result ['west_most_point' ] = result .geometry .bounds .minx
181202 result .sort_values (by = 'west_most_point' , ascending = flight_direction == 'DESCENDING' )
182203
@@ -190,11 +211,12 @@ def _get_frames_for_wkt(wkt: str, flight_direction: str) -> list[str]:
190211
191212 return [_pad_frame_str (frame ) for frame in frame_ids ]
192213
214+
193215def _pad_frame_str (frame : int ):
194216 frame_str = str (frame )
195217
196218 # append leading zeros
197219 if len (frame_str ) < 5 :
198- frame_str = ('0' * ( 5 - len (frame_str ))) + frame_str
220+ frame_str = ('0' * ( 5 - len (frame_str ))) + frame_str
199221
200222 return frame_str
0 commit comments