titipata commited on
Commit
254eed0
·
verified ·
1 Parent(s): bde1518

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -14
app.py CHANGED
@@ -53,21 +53,27 @@ def predict(img):
53
  as a dictionary:
54
  {label: confidence, label: confidence, ...}
55
  """
56
- if img is None:
57
- return None
58
 
59
- img_data = img['image']
60
- img_gray = Image.fromarray(img_data).convert('L').resize((28, 28))
61
- img_tensor = transforms.ToTensor()(img_gray).unsqueeze(0)
62
-
63
- # Make prediction
64
- with torch.no_grad():
65
- probs = model(img_tensor).softmax(dim=1).squeeze()
66
-
67
- probs, indices = torch.topk(probs, 5) # select top 5
68
- probs, indices = probs.tolist(), indices.tolist() # transform to list
69
- confidences = {LABELS[i]: float(v) for i, v in zip(indices, probs)}
70
- return confidences
 
 
 
 
 
 
 
71
 
72
 
73
  demo = gr.Interface(
 
53
  as a dictionary:
54
  {label: confidence, label: confidence, ...}
55
  """
56
+ print("Input type:", type(img))
 
57
 
58
+ try:
59
+ if img is None or not isinstance(img, dict) or 'image' not in img:
60
+ return {"Error": "Invalid input"}
61
+
62
+ img_data = img['image']
63
+ img_gray = Image.fromarray(img_data).convert('L').resize((28, 28))
64
+ img_tensor = transforms.ToTensor()(img_gray).unsqueeze(0)
65
+
66
+ # Make prediction
67
+ with torch.no_grad():
68
+ probs = model(img_tensor).softmax(dim=1).squeeze()
69
+
70
+ probs, indices = torch.topk(probs, 5) # select top 5
71
+ probs, indices = probs.tolist(), indices.tolist() # transform to list
72
+ confidences = {LABELS[i]: float(v) for i, v in zip(indices, probs)}
73
+ return confidences
74
+ except Exception as e:
75
+ print(f"Error in prediction: {str(e)}")
76
+ return {"Error": str(e)}
77
 
78
 
79
  demo = gr.Interface(