zliang commited on
Commit
b881458
1 Parent(s): 6ca10bc

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +11 -18
main.py CHANGED
@@ -1,20 +1,12 @@
1
  from fastapi import FastAPI, HTTPException
 
2
  from argopy import DataFetcher
3
  import matplotlib.pyplot as plt
4
- import uuid
5
- import os
6
 
7
  app = FastAPI()
8
 
9
- # Directory where images will be saved
10
- # This directory must be publicly accessible through your web server
11
- #image_directory = "/images"
12
- #os.makedirs(image_directory, exist_ok=True)
13
-
14
- # Base URL for the images
15
- # Replace with your server's base URL
16
- base_url = "https://zliang-argoapi.hf.space"
17
-
18
  @app.get("/plot_trajectory")
19
  def plot_trajectory(lon_min: float, lon_max: float, lat_min: float, lat_max: float,
20
  depth_min: float, depth_max: float,
@@ -27,21 +19,22 @@ def plot_trajectory(lon_min: float, lon_max: float, lat_min: float, lat_max: flo
27
  plt.figure()
28
  f.plot('trajectory', add_legend=False)
29
 
30
- # Save the plot to a file with a unique name
31
- filename = str(uuid.uuid4()) + ".png"
32
- plt.savefig(filename)
 
33
  plt.close()
34
 
35
- # Construct the URL for the saved image
36
- image_url = f"{base_url}/{filename}"
 
37
 
38
- return {"image_url": image_url}
39
 
40
  except Exception as e:
41
  raise HTTPException(status_code=500, detail=str(e))
42
 
43
 
44
-
45
  if __name__ == "__main__":
46
  import uvicorn
47
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
  from fastapi import FastAPI, HTTPException
2
+ from fastapi.responses import JSONResponse
3
  from argopy import DataFetcher
4
  import matplotlib.pyplot as plt
5
+ import io
6
+ import base64
7
 
8
  app = FastAPI()
9
 
 
 
 
 
 
 
 
 
 
10
  @app.get("/plot_trajectory")
11
  def plot_trajectory(lon_min: float, lon_max: float, lat_min: float, lat_max: float,
12
  depth_min: float, depth_max: float,
 
19
  plt.figure()
20
  f.plot('trajectory', add_legend=False)
21
 
22
+ # Save the plot to a BytesIO buffer
23
+ buf = io.BytesIO()
24
+ plt.savefig(buf, format='png')
25
+ buf.seek(0)
26
  plt.close()
27
 
28
+ # Encode the image in base64 and prepare it for JSON response
29
+ encoded_img = base64.b64encode(buf.read()).decode('utf-8')
30
+ response = {"image_base64": encoded_img}
31
 
32
+ return JSONResponse(content=response)
33
 
34
  except Exception as e:
35
  raise HTTPException(status_code=500, detail=str(e))
36
 
37
 
 
38
  if __name__ == "__main__":
39
  import uvicorn
40
  uvicorn.run(app, host="0.0.0.0", port=7860)