├── .bandit ├── .gitignore ├── samples ├── cat.jpg ├── dog.jpg ├── pizza.jpg ├── shuttle.jpg └── README.md ├── .dockerignore ├── requirements.txt ├── docs ├── swagger-screenshot.png └── deploy-max-to-ibm-cloud-with-kubernetes-button.png ├── requirements-test.txt ├── sha512sums.txt ├── .travis.yml ├── core ├── __init__.py └── model.py ├── api ├── __init__.py ├── metadata.py └── predict.py ├── max-inception-resnet-v2.yaml ├── app.py ├── Dockerfile ├── config.py ├── tests └── test.py ├── README.md └── LICENSE /.bandit: -------------------------------------------------------------------------------- 1 | [bandit] 2 | exclude: /tests,/training 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .pytest_cache/ 3 | __pycache__/ 4 | -------------------------------------------------------------------------------- /samples/cat.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/MAX-Inception-ResNet-v2/HEAD/samples/cat.jpg -------------------------------------------------------------------------------- /samples/dog.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/MAX-Inception-ResNet-v2/HEAD/samples/dog.jpg -------------------------------------------------------------------------------- /samples/pizza.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/MAX-Inception-ResNet-v2/HEAD/samples/pizza.jpg -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | README.* 2 | .idea/ 3 | .git/ 4 | .gitignore 5 | tests/ 6 | .pytest_cache 7 | tests/ 8 | -------------------------------------------------------------------------------- /samples/shuttle.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/MAX-Inception-ResNet-v2/HEAD/samples/shuttle.jpg -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy==1.17.5 2 | tensorflow==1.15.4 3 | Pillow==8.2.0 4 | h5py==2.9.0 5 | keras==2.1.4 6 | -------------------------------------------------------------------------------- /docs/swagger-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/MAX-Inception-ResNet-v2/HEAD/docs/swagger-screenshot.png -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | pytest==6.2.0 2 | requests==2.25.0 3 | flake8==3.8.4 4 | Pillow==8.2.0 5 | bandit==1.6.2 6 | -------------------------------------------------------------------------------- /docs/deploy-max-to-ibm-cloud-with-kubernetes-button.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/MAX-Inception-ResNet-v2/HEAD/docs/deploy-max-to-ibm-cloud-with-kubernetes-button.png -------------------------------------------------------------------------------- /sha512sums.txt: -------------------------------------------------------------------------------- 1 | 742bfc508d6c86072b0bfefd172f032789d632520f874dd3834420d39e41b5baf49102b2e603bcbc97633fd1c57e440a793cd53d9bba41f555984656da92a4ea assets/inception_resnet_v2.h5 -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - 3.6 4 | services: 5 | - docker 6 | install: 7 | - docker build -t max-inception-resnet-v2 . 8 | - docker run -it -d --rm -p 5000:5000 max-inception-resnet-v2 9 | - pip install -r requirements-test.txt 10 | before_script: 11 | - flake8 . --max-line-length=127 12 | - bandit -r . 13 | - sleep 90 14 | script: 15 | - pytest tests/test.py 16 | -------------------------------------------------------------------------------- /samples/README.md: -------------------------------------------------------------------------------- 1 | # Sample Assets 2 | 3 | ## Images 4 | 5 | All test images are from [Pexels](https://www.pexels.com) and licensed under a [CC0 License](https://creativecommons.org/publicdomain/zero/1.0/). 6 | 7 | * [`dog.jpg`](https://www.pexels.com/photo/adorable-animal-animal-photography-beagle-452772/) 8 | * [`cat.jpg`](https://www.pexels.com/photo/cat-whiskers-kitty-tabby-20787/) 9 | * [`shuttle.jpg`](https://www.pexels.com/photo/flight-sky-earth-space-2166/) 10 | * [`pizza.jpg`](https://www.pexels.com/photo/baked-pepperoni-pizza-774487/) 11 | -------------------------------------------------------------------------------- /core/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2018-2019 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | -------------------------------------------------------------------------------- /api/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2018-2019 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | from .metadata import ModelMetadataAPI # noqa 18 | from .predict import ModelPredictAPI # noqa 19 | -------------------------------------------------------------------------------- /max-inception-resnet-v2.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: max-inception-resnet-v2 5 | spec: 6 | selector: 7 | app: max-inception-resnet-v2 8 | ports: 9 | - port: 5000 10 | type: NodePort 11 | --- 12 | apiVersion: apps/v1 13 | kind: Deployment 14 | metadata: 15 | name: max-inception-resnet-v2 16 | labels: 17 | app: max-inception-resnet-v2 18 | spec: 19 | selector: 20 | matchLabels: 21 | app: max-inception-resnet-v2 22 | replicas: 1 23 | template: 24 | metadata: 25 | labels: 26 | app: max-inception-resnet-v2 27 | spec: 28 | containers: 29 | - name: max-inception-resnet-v2 30 | image: quay.io/codait/max-inception-resnet-v2:latest 31 | ports: 32 | - containerPort: 5000 33 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2018-2019 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | from maxfw.core import MAXApp 18 | from api import ModelMetadataAPI, ModelPredictAPI 19 | from config import API_TITLE, API_DESC, API_VERSION 20 | 21 | max_app = MAXApp(API_TITLE, API_DESC, API_VERSION) 22 | max_app.add_api(ModelMetadataAPI, '/metadata') 23 | max_app.add_api(ModelPredictAPI, '/predict') 24 | max_app.run() 25 | -------------------------------------------------------------------------------- /api/metadata.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2018-2019 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | from core.model import ModelWrapper 18 | from maxfw.core import MAX_API, MetadataAPI, METADATA_SCHEMA 19 | 20 | 21 | class ModelMetadataAPI(MetadataAPI): 22 | 23 | @MAX_API.marshal_with(METADATA_SCHEMA) 24 | def get(self): 25 | """Return the metadata associated with the model""" 26 | return ModelWrapper.MODEL_META_DATA 27 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2018-2019 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | FROM quay.io/codait/max-base:v1.4.0 18 | 19 | ARG model_bucket=https://max-cdn.cdn.appdomain.cloud/max-inception-resnet-v2/1.0 20 | ARG model_file=assets.tar.gz 21 | 22 | RUN wget -nv --show-progress --progress=bar:force:noscroll ${model_bucket}/${model_file} --output-document=assets/${model_file} && \ 23 | tar -x -C assets/ -f assets/${model_file} -v && rm assets/${model_file} && \ 24 | mkdir -p ~/.keras/models && mv assets/imagenet_class_index.json ~/.keras/models/imagenet_class_index.json 25 | 26 | COPY requirements.txt . 27 | RUN pip install -r requirements.txt 28 | 29 | COPY . . 30 | 31 | # check file integrity 32 | RUN sha512sum -c sha512sums.txt 33 | 34 | EXPOSE 5000 35 | 36 | CMD python app.py 37 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2018-2019 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | # Flask settings 18 | DEBUG = False 19 | 20 | # Flask-restplus settings 21 | RESTPLUS_MASK_SWAGGER = False 22 | SWAGGER_UI_DOC_EXPANSION = 'none' 23 | 24 | # API Metadata 25 | API_TITLE = 'MAX Image Classifier - Inception ResNet v2' 26 | API_DESC = 'Identify objects in images using a third-generation deep residual network.' 27 | API_VERSION = '1.2.0' 28 | 29 | # Model settings 30 | keras_builtin_models = { 31 | 'inception_v3': {'size': (299, 299), 'license': 'Apache v2'}, 32 | 'inception_resnet_v2': {'size': (299, 299), 'license': 'Apache v2'}, 33 | 'xception': {'size': (299, 299), 'license': 'MIT'}, 34 | 'resnet50': {'size': (224, 224), 'license': 'MIT'} 35 | } 36 | 37 | # default model 38 | MODEL_NAME = 'inception_resnet_v2' 39 | DEFAULT_MODEL_PATH = 'assets/{}.h5'.format(MODEL_NAME) 40 | MODEL_INPUT_IMG_SIZE = keras_builtin_models[MODEL_NAME]['size'] 41 | MODEL_LICENSE = keras_builtin_models[MODEL_NAME]['license'] 42 | 43 | MODEL_META_DATA = { 44 | 'id': '{}-keras-imagenet'.format(MODEL_NAME.lower()), 45 | 'name': '{} Keras Model'.format(MODEL_NAME), 46 | 'description': '{} Keras model trained on ImageNet'.format(MODEL_NAME), 47 | 'type': 'image_classification', 48 | 'license': MODEL_LICENSE, 49 | 'source': 'https://developer.ibm.com/exchanges/models/all/max-inception-resnet-v2/' 50 | } 51 | -------------------------------------------------------------------------------- /core/model.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2018-2019 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | from PIL import Image 18 | from keras.backend import clear_session 19 | from keras import models 20 | from keras.preprocessing.image import img_to_array 21 | from keras.applications import imagenet_utils 22 | import io 23 | import numpy as np 24 | import logging 25 | from flask import abort 26 | from config import DEFAULT_MODEL_PATH, MODEL_INPUT_IMG_SIZE, MODEL_META_DATA as model_meta 27 | from maxfw.model import MAXModelWrapper 28 | 29 | logger = logging.getLogger() 30 | 31 | 32 | class ModelWrapper(MAXModelWrapper): 33 | 34 | MODEL_META_DATA = model_meta 35 | 36 | def __init__(self, path=DEFAULT_MODEL_PATH): 37 | logger.info('Loading model from: {}...'.format(path)) 38 | clear_session() 39 | 40 | self.model = models.load_model(path) 41 | # this seems to be required to make Keras models play nicely with threads 42 | self.model._make_predict_function() 43 | logger.info('Loaded model: {}'.format(self.model.name)) 44 | 45 | def _read_image(self, image_data): 46 | try: 47 | image = Image.open(io.BytesIO(image_data)).convert('RGB') 48 | return image 49 | except IOError as e: 50 | logger.error(str(e)) 51 | abort(400, "The provided input is not a valid image (PNG or JPG required).") 52 | 53 | def _pre_process(self, image, target, mode='tf'): 54 | image = image.resize(target) 55 | image = img_to_array(image) 56 | image = np.expand_dims(image, axis=0) 57 | image = imagenet_utils.preprocess_input(image, mode=mode) 58 | return image 59 | 60 | def _post_process(self, preds): 61 | return imagenet_utils.decode_predictions(preds)[0] 62 | 63 | def _predict(self, x): 64 | x = self._pre_process(x, target=MODEL_INPUT_IMG_SIZE) 65 | preds = self.model.predict(x) 66 | return self._post_process(preds) 67 | -------------------------------------------------------------------------------- /api/predict.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2018-2019 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | from core.model import ModelWrapper 18 | from flask_restplus import fields 19 | from werkzeug.datastructures import FileStorage 20 | from maxfw.core import MAX_API, PredictAPI 21 | 22 | # Set up parser for input data (http://flask-restplus.readthedocs.io/en/stable/parsing.html) 23 | input_parser = MAX_API.parser() 24 | input_parser.add_argument('image', type=FileStorage, location='files', required=True, help="An image file (RGB/HWC)") 25 | 26 | 27 | label_prediction = MAX_API.model('LabelPrediction', { 28 | 'label_id': fields.String(required=False, description='Class label identifier'), 29 | 'label': fields.String(required=True, description='Class label'), 30 | 'probability': fields.Float(required=True, description='Predicted probability for the class label') 31 | }) 32 | 33 | 34 | predict_response = MAX_API.model('ModelPredictResponse', { 35 | 'status': fields.String(required=True, description='Response status message'), 36 | 'predictions': fields.List(fields.Nested(label_prediction), description='Predicted class labels and probabilities') 37 | }) 38 | 39 | 40 | class ModelPredictAPI(PredictAPI): 41 | 42 | model_wrapper = ModelWrapper() 43 | 44 | @MAX_API.doc('predict') 45 | @MAX_API.expect(input_parser) 46 | @MAX_API.marshal_with(predict_response) 47 | def post(self): 48 | """Make a prediction given input data""" 49 | result = {'status': 'error'} 50 | 51 | args = input_parser.parse_args() 52 | input_data = args['image'].read() 53 | image = self.model_wrapper._read_image(input_data) 54 | preds = self.model_wrapper._predict(image) 55 | 56 | # Modify this code if the schema is changed 57 | label_preds = [{'label_id': p[0], 'label': p[1], 'probability': p[2]} for p in [x for x in preds]] 58 | result['predictions'] = label_preds 59 | result['status'] = 'ok' 60 | 61 | return result 62 | -------------------------------------------------------------------------------- /tests/test.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2018-2019 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | import pytest 18 | import requests 19 | from PIL import Image 20 | import tempfile 21 | 22 | 23 | def test_swagger(): 24 | 25 | model_endpoint = 'http://localhost:5000/swagger.json' 26 | 27 | r = requests.get(url=model_endpoint) 28 | assert r.status_code == 200 29 | assert r.headers['Content-Type'] == 'application/json' 30 | 31 | json = r.json() 32 | assert 'swagger' in json 33 | assert json.get('info') and json.get('info').get('title') == 'MAX Image Classifier - Inception ResNet v2' 34 | assert json.get('info') and json.get('info').get('version') == '1.2.0' 35 | assert json.get('info') and json.get('info').get('description') == 'Identify objects in images using a ' \ 36 | 'third-generation deep residual network.' 37 | 38 | 39 | def test_metadata(): 40 | 41 | model_endpoint = 'http://localhost:5000/model/metadata' 42 | 43 | r = requests.get(url=model_endpoint) 44 | assert r.status_code == 200 45 | 46 | metadata = r.json() 47 | assert metadata['id'] == 'inception_resnet_v2-keras-imagenet' 48 | assert metadata['name'] == 'inception_resnet_v2 Keras Model' 49 | assert metadata['description'] == 'inception_resnet_v2 Keras model trained on ImageNet' 50 | assert metadata['license'] == 'Apache v2' 51 | 52 | 53 | def _check_predict(r): 54 | 55 | assert r.status_code == 200 56 | response = r.json() 57 | assert response['status'] == 'ok' 58 | assert response['predictions'][0]['label_id'] == 'n02123045' 59 | assert response['predictions'][0]['label'] == 'tabby' 60 | assert response['predictions'][0]['probability'] > 0.6 61 | 62 | 63 | def test_predict(): 64 | 65 | formats = ['JPEG', 'PNG'] 66 | model_endpoint = 'http://localhost:5000/model/predict' 67 | file_path = 'samples/cat.jpg' 68 | jpg = Image.open(file_path) 69 | 70 | for f in formats: 71 | temp = tempfile.TemporaryFile() 72 | if f == 'PNG': 73 | jpg.convert('RGBA').save(temp, f) 74 | else: 75 | jpg.save(temp, f) 76 | temp.seek(0) 77 | file_form = {'image': (file_path, temp, 'image/{}'.format(f.lower()))} 78 | r = requests.post(url=model_endpoint, files=file_form) 79 | _check_predict(r) 80 | 81 | 82 | def test_invalid_input(): 83 | 84 | model_endpoint = 'http://localhost:5000/model/predict' 85 | file_path = 'samples/README.md' 86 | 87 | with open(file_path, 'rb') as file: 88 | file_form = {'image': (file_path, file, 'image/jpeg')} 89 | r = requests.post(url=model_endpoint, files=file_form) 90 | 91 | assert r.status_code == 400 92 | response = r.json() 93 | assert 'input is not a valid image' in response['message'] 94 | 95 | 96 | if __name__ == '__main__': 97 | pytest.main([__file__]) 98 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/IBM/MAX-Inception-ResNet-v2.svg?branch=master)](https://travis-ci.org/IBM/MAX-Inception-ResNet-v2) [![Website Status](https://img.shields.io/website/http/max-inception-resnet-v2.codait-prod-41208c73af8fca213512856c7a09db52-0000.us-east.containers.appdomain.cloud/swagger.json.svg?label=api+demo)](http://max-inception-resnet-v2.codait-prod-41208c73af8fca213512856c7a09db52-0000.us-east.containers.appdomain.cloud) 2 | 3 | [](http://ibm.biz/max-to-ibm-cloud-tutorial) 4 | 5 | # IBM Code Model Asset Exchange: Inception-ResNet-v2 Image Classifier 6 | 7 | This repository contains code to instantiate and deploy an image classification model. This model recognizes the 1000 different classes of objects in the [ImageNet 2012 Large Scale Visual Recognition Challenge](http://www.image-net.org/challenges/LSVRC/2012/). The model consists of a deep convolutional net using the Inception-ResNet-v2 architecture that was trained on the ImageNet-2012 data set. The input to the model is a 299x299 image, and the output is a list of estimated class probabilities. 8 | 9 | The model is based on the [Keras built-in model for Inception-ResNet-v2](https://keras.io/applications/#inceptionresnetv2). The model files are hosted on [IBM Cloud Object Storage](https://max-cdn.cdn.appdomain.cloud/max-inception-resnet-v2/1.0/assets.tar.gz). The code in this repository deploys the model as a web service in a Docker container. This repository was developed as part of the [IBM Code Model Asset Exchange](https://developer.ibm.com/code/exchanges/models/) and the public API is powered by [IBM Cloud](https://ibm.biz/Bdz2XM). 10 | 11 | ## Model Metadata 12 | | Domain | Application | Industry | Framework | Training Data | Input Data Format | 13 | | ------------- | -------- | -------- | --------- | --------- | -------------- | 14 | | Vision | Image Classification | General | Keras | [ImageNet](http://www.image-net.org/) | Image (RGB/HWC)| 15 | 16 | ## References 17 | 18 | * _C. Szegedy, S. Ioffe, V. Vanhoucke, A. Alemi_, ["Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning"](https://arxiv.org/abs/1602.07261), CoRR (abs/1602.07261), 2016. 19 | * [Keras Applications](https://keras.io/applications/#inceptionresnetv2) 20 | 21 | ## Licenses 22 | 23 | | Component | License | Link | 24 | | ------------- | -------- | -------- | 25 | | This repository | [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) | [LICENSE](LICENSE) | 26 | | Model Weights | [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) | [Keras Inception-ResNet-v2](https://keras.io/applications/#inceptionresnetv2)| 27 | | Model Code (3rd party) | [MIT](https://opensource.org/licenses/MIT) | [Keras LICENSE](https://github.com/keras-team/keras/blob/master/LICENSE)| 28 | | Test assets | Various | [Samples README](samples/README.md) | 29 | 30 | ## Pre-requisites: 31 | 32 | * `docker`: The [Docker](https://www.docker.com/) command-line interface. Follow the [installation instructions](https://docs.docker.com/install/) for your system. 33 | * The minimum recommended resources for this model is 2GB Memory and 2 CPUs. 34 | * If you are on x86-64/AMD64, your CPU must support [AVX](https://en.wikipedia.org/wiki/Advanced_Vector_Extensions) at the minimum. 35 | 36 | # Deployment options 37 | 38 | * [Deploy from Quay](#deploy-from-quay) 39 | * [Deploy on Red Hat OpenShift](#deploy-on-red-hat-openshift) 40 | * [Deploy on Kubernetes](#deploy-on-kubernetes) 41 | * [Run Locally](#run-locally) 42 | 43 | ## Deploy from Quay 44 | 45 | To run the docker image, which automatically starts the model serving API, run: 46 | 47 | ``` 48 | $ docker run -it -p 5000:5000 quay.io/codait/max-inception-resnet-v2 49 | ``` 50 | 51 | This will pull a pre-built image from the Quay.io container registry (or use an existing image if already cached locally) and run it. 52 | If you'd rather checkout and build the model locally you can follow the [run locally](#run-locally) steps below. 53 | 54 | ## Deploy on Red Hat OpenShift 55 | 56 | You can deploy the model-serving microservice on Red Hat OpenShift by following the instructions for the OpenShift web console or the OpenShift Container Platform CLI [in this tutorial](https://developer.ibm.com/tutorials/deploy-a-model-asset-exchange-microservice-on-red-hat-openshift/), specifying `quay.io/codait/max-inception-resnet-v2` as the image name. 57 | 58 | ## Deploy on Kubernetes 59 | 60 | You can also deploy the model on Kubernetes using the latest docker image on Quay. 61 | 62 | On your Kubernetes cluster, run the following commands: 63 | 64 | ``` 65 | $ kubectl apply -f https://raw.githubusercontent.com/IBM/MAX-Inception-ResNet-v2/master/max-inception-resnet-v2.yaml 66 | ``` 67 | 68 | The model will be available internally at port `5000`, but can also be accessed externally through the `NodePort`. 69 | 70 | A more elaborate tutorial on how to deploy this MAX model to production on [IBM Cloud](https://ibm.biz/Bdz2XM) can be found [here](http://ibm.biz/max-to-ibm-cloud-tutorial). 71 | 72 | ## Run Locally 73 | 74 | 1. [Build the Model](#1-build-the-model) 75 | 2. [Deploy the Model](#2-deploy-the-model) 76 | 3. [Use the Model](#3-use-the-model) 77 | 4. [Development](#4-development) 78 | 5. [Cleanup](#5-cleanup) 79 | 80 | ### 1. Build the Model 81 | 82 | Clone this repository locally. In a terminal, run the following command: 83 | 84 | ``` 85 | $ git clone https://github.com/IBM/MAX-Inception-ResNet-v2.git 86 | ``` 87 | 88 | Change directory into the repository base folder: 89 | 90 | ``` 91 | $ cd MAX-Inception-ResNet-v2 92 | ``` 93 | 94 | To build the docker image locally, run: 95 | 96 | ``` 97 | $ docker build -t max-inception-resnet-v2 . 98 | ``` 99 | 100 | All required model assets will be downloaded during the build process. _Note_ that currently this docker image is CPU only (we will add support for GPU images later). 101 | 102 | 103 | ### 2. Deploy the Model 104 | 105 | To run the docker image, which automatically starts the model serving API, run: 106 | 107 | ``` 108 | $ docker run -it -p 5000:5000 max-inception-resnet-v2 109 | ``` 110 | 111 | ### 3. Use the Model 112 | 113 | The API server automatically generates an interactive Swagger documentation page. Go to `http://localhost:5000` to load it. From there you can explore the API and also create test requests. 114 | 115 | Use the `model/predict` endpoint to load a test image (you can use one of the test images from the `samples` folder) and get predicted labels for the image from the API. 116 | 117 | ![Swagger Doc Screenshot](docs/swagger-screenshot.png) 118 | 119 | You can also test it on the command line, for example: 120 | 121 | ``` 122 | $ curl -F "image=@samples/dog.jpg" -X POST http://localhost:5000/model/predict 123 | ``` 124 | 125 | You should see a JSON response like that below: 126 | 127 | ```json 128 | { 129 | "status": "ok", 130 | "predictions": [ 131 | { 132 | "label_id": "n02088364", 133 | "label": "beagle", 134 | "probability": 0.44505545496941 135 | }, 136 | { 137 | "label_id": "n02089867", 138 | "label": "Walker_hound", 139 | "probability": 0.3902231156826 140 | }, 141 | { 142 | "label_id": "n02089973", 143 | "label": "English_foxhound", 144 | "probability": 0.02027696929872 145 | }, 146 | { 147 | "label_id": "n02088632", 148 | "label": "bluetick", 149 | "probability": 0.010103852488101 150 | }, 151 | { 152 | "label_id": "n02088238", 153 | "label": "basset", 154 | "probability": 0.001649746671319 155 | } 156 | ] 157 | } 158 | ``` 159 | 160 | ### 4. Development 161 | 162 | To run the Flask API app in debug mode, edit `config.py` to set `DEBUG = True` under the application settings. You will then need to rebuild the docker image (see [step 1](#1-build-the-model)). 163 | 164 | ### 5. Cleanup 165 | 166 | To stop the Docker container, type `CTRL` + `C` in your terminal. 167 | 168 | ## Resources and Contributions 169 | 170 | If you are interested in contributing to the Model Asset Exchange project or have any queries, please follow the instructions [here](https://github.com/CODAIT/max-central-repo). 171 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------