Docker Image for Image prediction using Pytorch Image Models (timm)
I want to create a docker image for Image Prediction using Timm which gives outputs in JSON format like {&quot;predicted&quot;: &quot;cat&quot;, &quot;confidence&quot;: &quot;0.99&quot;}.
I am using this code.
from __future__ import print_function
import argparse
import torch
import timm
import urllib
import json
import torchvision.io as io
from PIL import Image as img
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform

# Training settings
parser = argparse.ArgumentParser(description='Assignment 1')
parser.add_argument('--model',type=str)
parser.add_argument('--image',type=str)

if __name__ =='__main__':
args =parser.parse_args()
model = timm.create_model(args.model,pretrained=True)
model.eval()
config = resolve_data_config({},model=model)
transform = create_transform(**config)

url, filename = (args.image, &quot;cat.jpg&quot;)
urllib.request.urlretrieve(url, filename)
img = img.open(filename).convert('RGB')
tensor = transform(img).unsqueeze(0)  # transform and add batch dimension
import torch
with torch.no_grad():
    out = model(tensor)
probabilities = torch.nn.functional.softmax(out[0], dim=0)
print({&quot;predicted&quot; : &quot;cat&quot;, &quot;confidence&quot; : f&quot;{int(probabilities.max()*100)/100}&quot;})

After running a test script, the output is:
Output is not valid json ! got: {'predicted': 'cat', 'confidence': '0.99'}

After using json.dump I am getting this error.
Traceback (most recent call last):
File &quot;/opt/src/main.py&quot;, line 25, in &lt;module&gt;
urllib.request.urlretrieve(url, filename)
File &quot;/usr/local/lib/python3.9/urllib/request.py&quot;, line 239, in 
urlretrieve
with contextlib.closing(urlopen(url, data)) as fp:
File &quot;/usr/local/lib/python3.9/urllib/request.py&quot;, line 214, in 
urlopen
return opener.open(url, data, timeout)
File &quot;/usr/local/lib/python3.9/urllib/request.py&quot;, line 523, in 
open
response = meth(req, response)
File &quot;/usr/local/lib/python3.9/urllib/request.py&quot;, line 632, in 
 http_response
response = self.parent.error(
File &quot;/usr/local/lib/python3.9/urllib/request.py&quot;, line 561, in 
error
return self._call_chain(*args)
File &quot;/usr/local/lib/python3.9/urllib/request.py&quot;, line 494, in 
_call_chain
result = func(*args)
File &quot;/usr/local/lib/python3.9/urllib/request.py&quot;, line 641, in 
http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden


You need to use json.dumps:
import json

...

print(json.dumps({&quot;predicted&quot; : &quot;cat&quot;, &quot;confidence&quot; : f&quot;{int(probabilities.max()*100)/100}&quot;}))


