Issue
I want to create a docker image for Image Prediction using Timm which gives outputs in JSON format like {"predicted": "cat", "confidence": "0.99"}.
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, "cat.jpg")
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({"predicted" : "cat", "confidence" : f"{int(probabilities.max()*100)/100}"})
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 "/opt/src/main.py", line 25, in <module>
urllib.request.urlretrieve(url, filename)
File "/usr/local/lib/python3.9/urllib/request.py", line 239, in
urlretrieve
with contextlib.closing(urlopen(url, data)) as fp:
File "/usr/local/lib/python3.9/urllib/request.py", line 214, in
urlopen
return opener.open(url, data, timeout)
File "/usr/local/lib/python3.9/urllib/request.py", line 523, in
open
response = meth(req, response)
File "/usr/local/lib/python3.9/urllib/request.py", line 632, in
http_response
response = self.parent.error(
File "/usr/local/lib/python3.9/urllib/request.py", line 561, in
error
return self._call_chain(*args)
File "/usr/local/lib/python3.9/urllib/request.py", line 494, in
_call_chain
result = func(*args)
File "/usr/local/lib/python3.9/urllib/request.py", line 641, in
http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
Solution
You need to use json.dumps
:
import json
...
print(json.dumps({"predicted" : "cat", "confidence" : f"{int(probabilities.max()*100)/100}"}))
Answered By - Danylo Baibak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.