page_type | languages | products | description | urlFragment | |||
---|---|---|---|---|---|---|---|
sample |
|
|
Predict ImageNet Classes with PyTorch and Azure Functions |
functions-python-pytorch-tutorial |
Note, the instructions below assume you are using a Linux environment.
mkdir start
cd start
python -m venv .venv
source .venv/bin/activate
func init --worker-runtime python
func new --name classify --template "HTTP trigger"
cp ../resources/predict.py classify
cp ../resources/labels.txt classify
- Add the following dependencies to start/requirements.txt, installing some numerical libraries and PyTorch itself:
azure-functions
requests
numpy==1.15.4
https://download.pytorch.org/whl/cpu/torch-1.4.0%2Bcpu-cp36-cp36m-win_amd64.whl; sys_platform == 'win32' and python_version == '3.6'
https://download.pytorch.org/whl/cpu/torch-1.4.0%2Bcpu-cp36-cp36m-linux_x86_64.whl; sys_platform == 'linux' and python_version == '3.6'
https://download.pytorch.org/whl/cpu/torch-1.4.0%2Bcpu-cp37-cp37m-win_amd64.whl; sys_platform == 'win32' and python_version == '3.7'
https://download.pytorch.org/whl/cpu/torch-1.4.0%2Bcpu-cp37-cp37m-linux_x86_64.whl; sys_platform == 'linux' and python_version == '3.7'
https://download.pytorch.org/whl/cpu/torch-1.4.0%2Bcpu-cp38-cp38-win_amd64.whl; sys_platform == 'win32' and python_version == '3.8'
https://download.pytorch.org/whl/cpu/torch-1.4.0%2Bcpu-cp38-cp38-linux_x86_64.whl; sys_platform == 'linux' and python_version == '3.8'
torchvision==0.5.0
- Install dependencies with
pip install --no-cache-dir -r requirements.txt
- Add an
import
statement toclassify/__init__.py
import logging
import json
import azure.functions as func
from .predict import predict_image_from_url
- Replace the entire contents of the
main
function with the following code:
def main(req: func.HttpRequest) -> func.HttpResponse:
image_url = req.params.get('img')
logging.info('Image URL received: ' + image_url)
results = predict_image_from_url(image_url)
headers = {
"Content-type": "application/json",
"Access-Control-Allow-Origin": "*"
}
return func.HttpResponse(json.dumps(results), headers = headers)
- Run
func start
from within the start folder with the virtual environment activated. - Run
http://localhost:7071/api/classify?img=https://raw.githubusercontent.com/gvashishtha/functions-pytorch/master/resources/assets/Bernese-Mountain-Dog-Temperament-long.jpg
func azure functionapp publish <appname> --build local
- Test by using the suggested URL and appending
&img=https://raw.githubusercontent.com/gvashishtha/functions-pytorch/master/resources/assets/Bernese-Mountain-Dog-Temperament-long.jpg
at the end of the query string.
See LICENSE.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.