Muhammad Ahad Hassan Khan commited on
Commit
65a47c9
·
1 Parent(s): 93a18ad

.npy and png in zip output

Browse files
Files changed (1) hide show
  1. app.py +26 -21
app.py CHANGED
@@ -1,13 +1,10 @@
1
- # app.py
2
- from fastapi import FastAPI, File, UploadFile
3
  from fastapi.responses import StreamingResponse, JSONResponse
 
4
  from ndvi_predictor import load_model, normalize_rgb, predict_ndvi, create_visualization
5
  from PIL import Image
6
  from io import BytesIO
7
  import numpy as np
8
- import io
9
- import os
10
- import base64
11
 
12
  app = FastAPI()
13
  model = load_model("ndvi_best_model.keras")
@@ -25,22 +22,30 @@ async def predict_ndvi_api(file: UploadFile = File(...)):
25
  norm_img = normalize_rgb(np.array(img))
26
  pred_ndvi = predict_ndvi(model, norm_img)
27
 
28
- # Create preview (small visualization)
29
- img_io = create_visualization(norm_img, pred_ndvi)
30
- img_io.seek(0)
31
- preview_img = Image.open(img_io)
32
- preview_img.thumbnail((256, 256)) # Resize for fast rendering
33
- preview_bytes = BytesIO()
34
- preview_img.save(preview_bytes, format="PNG")
35
- preview_bytes.seek(0)
36
-
37
- img_base64 = base64.b64encode(preview_bytes.read()).decode("utf-8")
38
- ndvi_array = pred_ndvi.tolist() # Convert NumPy array to list
39
-
40
- return {
41
- "preview_base64": img_base64,
42
- "ndvi_array": ndvi_array # This can be big depending on image size
43
- }
 
 
 
 
 
 
 
 
44
 
45
  except Exception as e:
46
  return JSONResponse(status_code=500, content={"error": str(e)})
 
 
 
1
  from fastapi.responses import StreamingResponse, JSONResponse
2
+ from fastapi import FastAPI, File, UploadFile
3
  from ndvi_predictor import load_model, normalize_rgb, predict_ndvi, create_visualization
4
  from PIL import Image
5
  from io import BytesIO
6
  import numpy as np
7
+ import zipfile
 
 
8
 
9
  app = FastAPI()
10
  model = load_model("ndvi_best_model.keras")
 
22
  norm_img = normalize_rgb(np.array(img))
23
  pred_ndvi = predict_ndvi(model, norm_img)
24
 
25
+ # Visualization image as PNG
26
+ vis_img_bytes = create_visualization(norm_img, pred_ndvi)
27
+ vis_img_bytes.seek(0)
28
+
29
+ # NDVI band as .npy
30
+ ndvi_bytes = BytesIO()
31
+ np.save(ndvi_bytes, pred_ndvi)
32
+ ndvi_bytes.seek(0)
33
+
34
+ # Create a ZIP containing both files
35
+
36
+ zip_buf = BytesIO()
37
+ with zipfile.ZipFile(zip_buf, "w") as zip_file:
38
+ zip_file.writestr("ndvi_image.png", vis_img_bytes.read())
39
+ ndvi_bytes.seek(0)
40
+ zip_file.writestr("ndvi_band.npy", ndvi_bytes.read())
41
+
42
+ zip_buf.seek(0)
43
+
44
+ return StreamingResponse(
45
+ zip_buf,
46
+ media_type="application/x-zip-compressed",
47
+ headers={"Content-Disposition": "attachment; filename=ndvi_output.zip"}
48
+ )
49
 
50
  except Exception as e:
51
  return JSONResponse(status_code=500, content={"error": str(e)})