I have 4 human face emotion classifier models implenet using mobilenet,resnet,shufflenet,squeezee net stored using .pth now I want to deploy this model using docker such that it takes images input and gives prediction output for different model which will be chosen by user (give steps with code to implement this)
Assistant
To deploy your 4 human face emotion classifier models using Docker, follow these steps:
Create a Flask app to serve your models.
Create a Dockerfile.
Build a Docker image.
Run the Docker container.
1. Create a Flask app to serve your models
First, you'll need to create a simple Flask app to load and serve your models for inference. Install Flask if you haven't already:
bash
pip install Flask
Create a file named app.py and add the following code:
python
from flask import Flask, request, jsonify
import torch
from torchvision import transforms
from PIL import Image
app = Flask(__name__)
# Load models
MODEL_NAME_DICT = {
"mobilenet": "mobilenet.pth",
"resnet": "resnet.pth",
"shufflenet": "shufflenet.pth",
"squeezenet": "squeezenet.pth",
}
MODEL_MAP = {}
for model_name, model_path in MODEL_NAME_DICT.items():
MODEL_MAP[model_name] = torch.load(model_path, map_location=torch.device('cpu'))
# Pre-processing
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
@app.route('/predict', methods=['POST'])
def predict():
if request.method == 'POST':
if 'file' not in request.files:
return jsonify({"error": "No image provided."}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No image provided."}), 400
img = Image.open(file)
model_name = request.form.get('model', 'mobilenet')
if model_name not in MODEL_MAP:
return jsonify({"error": f"Invalid model name: {model_name}. Choose from {', '.join(MODEL_NAME_DICT.keys())}"}), 400
model = MODEL_MAP[model_name]
# Image pre-processing
input_tensor = transform(img)
input_batch = input_tensor.unsqueeze(0)
# Run prediction
with torch.no_grad():
output = model(input_batch)
_, predicted = torch.max(output, 1)
prediction = int(predicted)
return jsonify({"prediction": prediction})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
This Flask app includes a single route /predict that accepts an image file and an optional model name. It loads the models as specified in the MODEL_NAME_DICT variable and maps them to the MODEL_MAP variable.
2. Create a Dockerfile
Create a new file named Dockerfile in the same directory as your app.py file and add the following content:
code
# Use the official PyTorch image as the base image
FROM pytorch/pytorch:1.10.0-cuda11.3-cudnn8-runtime
# Set the working directory
WORKDIR /app
# Copy requirements.txt
COPY requirements.txt /app/requirements.txt
# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt
# Copy the rest of the application files
COPY . /app
# Expose the inbound port for the API
EXPOSE 5000
# Run the application
CMD ["python", "app.py"]
This Dockerfile specifies the base image as pytorch/pytorch for PyTorch and CUDA support, sets the working directory, copies the requirements file, installs the required packages, and exposes port 5000.
Create a requirements.txt file with the following content: