Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import onnxruntime as ort
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import time
|
| 6 |
+
import logging
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
logging.basicConfig(level=logging.INFO)
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
model_path = "model.onnx"
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
start_time = time.perf_counter()
|
| 16 |
+
model = ort.InferenceSession(model_path, providers=["CUDAExecutionProvider", "CPUExecutionProvider"])
|
| 17 |
+
logger.info(f"Model successfully loaded from {model_path} in {time.perf_counter()-start_time:.2f} sec")
|
| 18 |
+
|
| 19 |
+
except Exception as e:
|
| 20 |
+
logger.error(f"Failed to load model from {model_path}: {e}")
|
| 21 |
+
|
| 22 |
+
def preprocess_image(image):
|
| 23 |
+
"Convert to rgb, normalize and add batch dimension"
|
| 24 |
+
img = Image.open(image).convert("RGB")
|
| 25 |
+
img_arr = np.array(img, dtype=np.float32) / 255.0
|
| 26 |
+
img_arr = np.expand_dims(img_arr, axis=0)
|
| 27 |
+
|
| 28 |
+
return img_arr
|
| 29 |
+
|
| 30 |
+
def super_resolution_image(image):
|
| 31 |
+
try:
|
| 32 |
+
model_inputs = model.get_inputs()[0].name
|
| 33 |
+
model_outputs = model.get_outputs()[0].name
|
| 34 |
+
# Inference
|
| 35 |
+
sr_img = model.run([model_outputs], {model_inputs: image})[0]
|
| 36 |
+
# Postprocess
|
| 37 |
+
sr_img = (np.clip(sr_img, 0, 1)*255).astype(np.uint8)
|
| 38 |
+
return Image.fromarray(sr_img[0])
|
| 39 |
+
|
| 40 |
+
except Exception as e:
|
| 41 |
+
raise RuntimeError(f"Model inference failed, {str(e)}")
|
| 42 |
+
|
| 43 |
+
def gradio_inference(image):
|
| 44 |
+
img_arr = preprocess_image(image)
|
| 45 |
+
sr_img = super_resolution_image(img_arr)
|
| 46 |
+
return sr_img
|
| 47 |
+
|
| 48 |
+
demo = gr.Interface(
|
| 49 |
+
fn=gradio_inference,
|
| 50 |
+
inputs=gr.Image(type="filepath"),
|
| 51 |
+
outputs="image",
|
| 52 |
+
title="EDSR 4x Super-Resolution",
|
| 53 |
+
description="Upscale your images 4× using an onnx edsr model"
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
if __name__ == "__main__":
|
| 57 |
+
demo.launch()
|