vValentine7 commited on
Commit
6fa98e5
·
verified ·
1 Parent(s): 783c5e1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, Response
2
+ from pydantic import BaseModel
3
+ import io
4
+ import base64
5
+ import blosc
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+
9
+ # --- App and Pydantic Model Setup ---
10
+
11
+ app = FastAPI()
12
+
13
+ class BinaryPayload(BaseModel):
14
+ file_data: str
15
+ dtype: str = 'float32'
16
+ shape: tuple[int, int] = (720, 1440)
17
+ cmap: str = 'plasma'
18
+
19
+ # --- Helper Function ---
20
+
21
+ def normalize(arr: np.ndarray, lo: float, hi: float) -> np.ndarray:
22
+ """Normalizes a NumPy array to the 0-1 range for visualization."""
23
+ return np.clip((arr - lo) / (hi - lo), 0, 1)
24
+
25
+ # --- API Endpoints ---
26
+
27
+ @app.get("/")
28
+ def home():
29
+ return {"message": "Binary to PNG Conversion API is live."}
30
+
31
+ @app.post("/render-from-binary")
32
+ async def render_from_binary(payload: BinaryPayload):
33
+ """
34
+ Accepts a base64-encoded, Blosc-compressed binary chunk
35
+ and returns it as a rendered PNG image.
36
+ """
37
+ try:
38
+ # Decode the base64 string
39
+ compressed_data = base64.b64decode(payload.file_data)
40
+
41
+ # Decompress the data using Blosc
42
+ decompressed_data = blosc.decompress(compressed_data)
43
+
44
+ # Interpret bytes as a NumPy array and reshape it
45
+ image_array = np.frombuffer(decompressed_data, dtype=payload.dtype)
46
+ image_array = image_array.reshape(payload.shape)
47
+
48
+ # Normalize the array for proper color mapping
49
+ vmin = float(np.nanmin(image_array))
50
+ vmax = float(np.nanmax(image_array))
51
+ normalized_frame = normalize(image_array, vmin, vmax)
52
+
53
+ # Generate the PNG image using Matplotlib
54
+ img_buf = io.BytesIO()
55
+ fig, ax = plt.subplots(figsize=(6, 3), dpi=240)
56
+ ax.imshow(normalized_frame, cmap=payload.cmap, origin="upper")
57
+ ax.axis("off")
58
+ plt.savefig(img_buf, format="png", bbox_inches="tight", pad_inches=0)
59
+ plt.close(fig)
60
+ img_buf.seek(0)
61
+
62
+ # Return the image as a response
63
+ return Response(content=img_buf.read(), media_type="image/png")
64
+
65
+ except base64.binascii.Error as e:
66
+ raise HTTPException(status_code=400, detail=f"Invalid base64 string: {e}")
67
+ except Exception as e:
68
+ raise HTTPException(status_code=400, detail=f"Failed to process binary data: {e}")