File size: 1,419 Bytes
674ae47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d88203
674ae47
 
 
 
 
 
 
 
 
6be24a2
674ae47
 
 
b7139a4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from base64 import b64encode
from io import BytesIO
from pathlib import Path

import numpy as np
from basicsr.archs.rrdbnet_arch import RRDBNet
from PIL import Image
from realesrgan import RealESRGANer


class EndpointHandler:
    def __init__(self, path=""):
        model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
        self.upsampler = RealESRGANer(
            scale=4,
            model_path=str(Path(path) / "RealESRGAN_x4plus.pth"),
            model=model,
            tile=0,
            tile_pad=10,
            pre_pad=0,
            half=True,
        )

    def __call__(self, data):
        """
        Args:
            data (:obj:):
                includes the input data and the parameters for the inference.
        Return:
            A :obj:`dict`:. base64 encoded image
        """
        image = data.pop("inputs", data)
        # image = Image.open(BytesIO(image)).convert("RGB")
        image = np.array(image)
        image = image[:, :, ::-1]  # RGB -> BGR

        image, _ = self.upsampler.enhance(image, outscale=4)
        image = image[:, :, ::-1]  # BGR -> RGB
        image = Image.fromarray(image)

        # encode image as base 64
        buffered = BytesIO()
        image.save(buffered, format="PNG")
        img_str = b64encode(buffered.getvalue())

        # postprocess the prediction
        return {"image": img_str.decode()}