Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tensorflow.keras.models import load_model
|
| 2 |
+
from fastapi import FastAPI, UploadFile, File
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import io
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
# Load the model with custom mse
|
| 10 |
+
model = load_model("super_resolution_model.h5", custom_objects={"mse": "mse"})
|
| 11 |
+
|
| 12 |
+
def preprocess_image(image: Image.Image):
|
| 13 |
+
# Adjust based on your model's input requirements
|
| 14 |
+
# Example: Resize to 64x64, normalize to [0, 1]
|
| 15 |
+
image = image.resize((64, 64)) # Replace with your model's input size
|
| 16 |
+
image_array = np.array(image) / 255.0
|
| 17 |
+
return np.expand_dims(image_array, axis=0)
|
| 18 |
+
|
| 19 |
+
def postprocess_image(output_array: np.ndarray):
|
| 20 |
+
# Adjust based on your model's output
|
| 21 |
+
# Example: Clip values, convert to uint8
|
| 22 |
+
output_array = np.clip(output_array[0] * 255.0, 0, 255).astype("uint8")
|
| 23 |
+
return Image.fromarray(output_array)
|
| 24 |
+
|
| 25 |
+
@app.post("/predict")
|
| 26 |
+
async def predict(file: UploadFile = File(...)):
|
| 27 |
+
# Read and preprocess image
|
| 28 |
+
image = Image.open(io.BytesIO(await file.read())).convert("RGB")
|
| 29 |
+
input_array = preprocess_image(image)
|
| 30 |
+
|
| 31 |
+
# Run inference
|
| 32 |
+
high_res = model.predict(input_array)
|
| 33 |
+
|
| 34 |
+
# Postprocess output
|
| 35 |
+
high_res_image = postprocess_image(high_res)
|
| 36 |
+
|
| 37 |
+
# Save to bytes
|
| 38 |
+
output = io.BytesIO()
|
| 39 |
+
high_res_image.save(output, format="PNG")
|
| 40 |
+
output.seek(0)
|
| 41 |
+
|
| 42 |
+
return {"image": output.getvalue()}
|
| 43 |
+
|
| 44 |
+
@app.get("/")
|
| 45 |
+
def root():
|
| 46 |
+
return {"message": "Super-resolution API"}
|