# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

'''
This script is an updated version for SINGA ONNX VGG16 infernece in `cpu` environment with Docker, e.g. AWS Lambda Docker Images.
I rewrote the device assignment to avoid Segmentation Faults. 
The above mentioned problematic function exists as singa.Axpy(), which points to Singa Optimizer apply() in https://github.com/apache/singa/blob/dev/python/singa/opt.py#L269 
and https://github.com/apache/singa/blob/master/src/model/optimizer/optimizer.cc & https://github.com/apache/singa/blob/master/src/model/optimizer/sgd.cc.
'''

import os
import numpy as np
from PIL import Image
import time
from singa import device
from singa import tensor
from singa import autograd
from singa import sonnx
import onnx
import urllib.request
import tarfile
import glob
import onnx
from onnx import numpy_helper

def check_exist_or_download(url):
    download_dir = '/tmp/'
    name = url.rsplit('/', 1)[-1]
    filename = os.path.join(download_dir, name)
    if not os.path.isfile(filename):
       urllib.request.urlretrieve(url, filename) # logging.info("Downloading %s" % url)
    return filename

def download_model(url):
    download_dir = '/tmp/'
    with tarfile.open(check_exist_or_download(url), 'r') as t:
        t.extractall(path=download_dir)

def get_image_labe():
    label_url = 'https://s3.amazonaws.com/onnx-model-zoo/synset.txt'
    with open(check_exist_or_download(label_url), 'r') as f:
        labels = [l.rstrip() for l in f]

    image_url = 'https://s3.amazonaws.com/model-server/inputs/kitten.jpg'
    img = Image.open(check_exist_or_download(image_url))
    return img, labels

def preprocess(img):
    img = img.resize((256, 256))
    img = img.crop((16, 16, 240, 240))
    img = np.array(img).astype(np.float32) / 255.
    img = np.rollaxis(img, 2, 0)
    for channel, mean, std in zip(range(3), [0.485, 0.456, 0.406],
                                  [0.229, 0.224, 0.225]):
        img[channel, :, :] -= mean
        img[channel, :, :] /= std
    img = np.expand_dims(img, axis=0)
    return img

class MyModel(sonnx.SONNXModel):

    def __init__(self, onnx_model):
        super(MyModel, self).__init__(onnx_model)
        self.SerializeToString = None

    def forward(self, *x):
        y = super(MyModel, self).forward(*x)
        return y[0]

    def train_one_batch(self, x, y):
        pass

def handler(event=None, context=None):
    class Infer:
        def __init__(self, sg_ir):
            self.sg_ir = sg_ir

        def forward(self, x):
            print ('forwarding ...')
            return sg_ir.run([x])[0]

    url = 'https://s3.amazonaws.com/onnx-model-zoo/vgg/vgg16/vgg16.tar.gz'
    download_dir = '/tmp/'
    model_path = os.path.join(download_dir, url.rsplit('/', 1)[-1].split('.', 1)[0], url.rsplit('/', 1)[-1].split('.', 1)[0]+'.onnx')

    # inference one picture
    img, labels = get_image_labe()
    img = preprocess(img)

    print("onnx load model...") 
    download_model(url)
    onnx_model = onnx.load(model_path)

    print("model running...")
    x_batch=img.astype(tensor.Tensor)

    model = MyModel(onnx_model)
    dev = device.get_default_device()
    x = tensor.PlaceHolder(img.shape, device=dev)
    model.compile([x], is_train=False, use_graph=True, sequential=True)
    x = tensor.Tensor(device=dev, data=img)
    y = model.forward(x)
    y = tensor.softmax(y)
    scores = tensor.to_numpy(y)
    scores = np.squeeze(scores)
    a = np.argsort(scores)[::-1]
    for i in a[0:5]:
        print('class=%s ; probability=%f' % (labels[i], scores[i]))

if __name__ == "__main__":
    handler(None,None)

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

'''
This script is an updated version for SINGA ONNX VGG16 infernece in `cpu` environment with Docker, e.g. AWS Lambda Docker Images.
I rewrote the device assignment to avoid Segmentation Faults. 
The above mentioned problematic function exists as singa.Axpy(), which points to Singa Optimizer apply() in https://github.com/apache/singa/blob/dev/python/singa/opt.py#L269 
and https://github.com/apache/singa/blob/master/src/model/optimizer/optimizer.cc & https://github.com/apache/singa/blob/master/src/model/optimizer/sgd.cc.
'''

import os
import numpy as np
from PIL import Image
import time
from singa import device
from singa import tensor
from singa import autograd
from singa import sonnx
import onnx
import urllib.request
import tarfile
import glob
import onnx
from onnx import numpy_helper

def check_exist_or_download(url):
    download_dir = '/tmp/'
    name = url.rsplit('/', 1)[-1]
    filename = os.path.join(download_dir, name)
    if not os.path.isfile(filename):
       urllib.request.urlretrieve(url, filename) # logging.info("Downloading %s" % url)
    return filename

def download_model(url):
    download_dir = '/tmp/'
    with tarfile.open(check_exist_or_download(url), 'r') as t:
        t.extractall(path=download_dir)

def get_image_labe():
    label_url = 'https://s3.amazonaws.com/onnx-model-zoo/synset.txt'
    with open(check_exist_or_download(label_url), 'r') as f:
        labels = [l.rstrip() for l in f]

    image_url = 'https://s3.amazonaws.com/model-server/inputs/kitten.jpg'
    img = Image.open(check_exist_or_download(image_url))
    return img, labels

def preprocess(img):
    img = img.resize((256, 256))
    img = img.crop((16, 16, 240, 240))
    img = np.array(img).astype(np.float32) / 255.
    img = np.rollaxis(img, 2, 0)
    for channel, mean, std in zip(range(3), [0.485, 0.456, 0.406],
                                  [0.229, 0.224, 0.225]):
        img[channel, :, :] -= mean
        img[channel, :, :] /= std
    img = np.expand_dims(img, axis=0)
    return img

class MyModel(sonnx.SONNXModel):

    def __init__(self, onnx_model):
        super(MyModel, self).__init__(onnx_model)
        self.SerializeToString = None

    def forward(self, *x):
        y = super(MyModel, self).forward(*x)
        return y[0]

    def train_one_batch(self, x, y):
        pass

def handler(event=None, context=None):
    class Infer:
        def __init__(self, sg_ir):
            self.sg_ir = sg_ir

        def forward(self, x):
            print ('forwarding ...')
            return sg_ir.run([x])[0]

    url = 'https://s3.amazonaws.com/onnx-model-zoo/vgg/vgg16/vgg16.tar.gz'
    download_dir = '/tmp/'
    model_path = os.path.join(download_dir, url.rsplit('/', 1)[-1].split('.', 1)[0], url.rsplit('/', 1)[-1].split('.', 1)[0]+'.onnx')

    # inference one picture
    img, labels = get_image_labe()
    img = preprocess(img)

    print("onnx load model...") 
    download_model(url)
    onnx_model = onnx.load(model_path)

    print("model running...")
    x_batch=img.astype(tensor.Tensor)

    model = MyModel(onnx_model)
    dev = device.get_default_device()
    x = tensor.PlaceHolder(img.shape, device=dev)
    model.compile([x], is_train=False, use_graph=True, sequential=True)
    x = tensor.Tensor(device=dev, data=img)
    y = model.forward(x)
    y = tensor.softmax(y)
    scores = tensor.to_numpy(y)
    scores = np.squeeze(scores)
    a = np.argsort(scores)[::-1]
    for i in a[0:5]:
        print('class=%s ; probability=%f' % (labels[i], scores[i]))

if __name__ == "__main__":
    handler(None,None)

# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements.  See the NOTICE file # distributed with this work for additional information # regarding copyright ownership.  The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License.  You may obtain a copy of the License at # #   http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied.  See the License for the # specific language governing permissions and limitations # under the License. This script is an updated version for SINGA ONNX VGG16 infernece in `cpu` environment with Docker, e.g. AWS Lambda Docker Images. I rewrote the device assignment to avoid Segmentation Faults.  The above mentioned problematic function exists as singa.Axpy(), which points to Singa Optimizer apply() in https://github.com/apache/singa/blob/dev/python/singa/opt.py#L269  and https://github.com/apache/singa/blob/master/src/model/optimizer/optimizer.cc & https://github.com/apache/singa/blob/master/src/model/optimizer/sgd.cc. # logging.info("Downloading %s" % url) # inference one picture