|
| 1 | +import io |
| 2 | +import traceback |
| 3 | +from typing import Annotated |
| 4 | + |
| 5 | +import fastapi |
| 6 | +import matplotlib |
| 7 | + |
| 8 | +matplotlib.use("AGG") |
| 9 | + |
| 10 | +import matplotlib.pyplot as plt |
| 11 | +import uvicorn |
| 12 | +from fastapi import BackgroundTasks, Body |
| 13 | +from fastapi.responses import Response |
| 14 | +from pydantic_shapely import FeatureBaseModel, GeometryField |
| 15 | +from shapely import LineString |
| 16 | +from src.transsect_plot import plot_transsect |
| 17 | + |
| 18 | +app = fastapi.FastAPI( |
| 19 | + title="Delta DTM Line Plot API", |
| 20 | + description="API for generating elevation profile plots along a transect line", |
| 21 | + version="1.0.0", |
| 22 | +) |
| 23 | + |
| 24 | + |
| 25 | +class LineStringModel(FeatureBaseModel, geometry_field="line"): |
| 26 | + line: Annotated[LineString, GeometryField()] |
| 27 | + |
| 28 | + |
| 29 | +@app.post( |
| 30 | + "/line-plot", |
| 31 | + response_class=Response, |
| 32 | + summary="Generate an elevation profile plot along a transect line", |
| 33 | + description="Takes a LineString geometry and returns a plot of the elevation profile along that line", |
| 34 | + responses={ |
| 35 | + 200: { |
| 36 | + "content": {"image/png": {}}, |
| 37 | + "description": "A PNG image of the elevation profile plot", |
| 38 | + }, |
| 39 | + 500: { |
| 40 | + "description": "Internal server error", |
| 41 | + }, |
| 42 | + }, |
| 43 | +) |
| 44 | +async def line_plot( |
| 45 | + line_string: Annotated[ |
| 46 | + LineStringModel.GeoJsonDataModel, # type: ignore |
| 47 | + Body( |
| 48 | + example={ |
| 49 | + "type": "Feature", |
| 50 | + "geometry": { |
| 51 | + "type": "LineString", |
| 52 | + "coordinates": [[4.9, 52.37], [5.12, 52.09]], |
| 53 | + }, |
| 54 | + "properties": {}, |
| 55 | + } |
| 56 | + ), |
| 57 | + ], |
| 58 | + background_tasks: BackgroundTasks, |
| 59 | +) -> Response: |
| 60 | + try: |
| 61 | + # Use the existing plot_transsect function to generate the figure |
| 62 | + line: LineString = line_string.geometry.to_shapely() |
| 63 | + fig = await plot_transsect(line) |
| 64 | + |
| 65 | + # Create an in-memory bytes buffer |
| 66 | + buf = io.BytesIO() |
| 67 | + |
| 68 | + # Save the figure to the in-memory buffer |
| 69 | + fig.savefig(buf, format="png") |
| 70 | + |
| 71 | + # Close the figure to free up resources |
| 72 | + plt.close(fig) |
| 73 | + |
| 74 | + # Seek to the beginning of the buffer |
| 75 | + buf.seek(0) |
| 76 | + |
| 77 | + # Return the image as a response with appropriate headers |
| 78 | + background_tasks.add_task(buf.close) |
| 79 | + background_tasks.add_task(plt.close, fig) |
| 80 | + return Response( |
| 81 | + content=buf.getvalue(), |
| 82 | + media_type="image/png", |
| 83 | + headers={"Content-Disposition": 'attachment; filename="transect_plot.png"'}, |
| 84 | + ) |
| 85 | + except Exception as e: |
| 86 | + # Log the error |
| 87 | + print("Error generating plot:") |
| 88 | + print(traceback.format_exc()) |
| 89 | + # Raise an HTTP exception |
| 90 | + raise fastapi.HTTPException( |
| 91 | + status_code=500, |
| 92 | + detail=f"Error generating plot: {str(e)}", |
| 93 | + ) |
| 94 | + |
| 95 | + |
| 96 | +@app.get("/", include_in_schema=False) |
| 97 | +async def root(): |
| 98 | + return { |
| 99 | + "message": "Welcome to the Delta DTM Line Plot API. Use /line-plot endpoint to generate elevation profile plots." |
| 100 | + } |
| 101 | + |
| 102 | + |
| 103 | +if __name__ == "__main__": |
| 104 | + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) |
0 commit comments