bhaveshgoel07 commited on
Commit
c4d114a
·
1 Parent(s): 983f76a

Fixed errors

Browse files
Files changed (1) hide show
  1. app.py +17 -6
app.py CHANGED
@@ -39,22 +39,33 @@ transform = transforms.Compose([
39
  # Prediction function
40
 
41
 
42
- def predict(image_dict):
 
43
  try:
44
- # Convert the dictionary to a PIL Image
45
- image = Image.fromarray(np.uint8(image_dict["image"])).convert('RGB')
 
 
 
 
 
 
 
46
 
47
- # Apply the transformation
48
- image = transform(image).unsqueeze(0) # Add batch dimension
 
49
 
50
  with torch.no_grad():
51
- output = model(image)
52
  probabilities = nn.Softmax(dim=1)(output)
53
 
54
  # Return the probabilities as a dictionary
55
  return {str(i): float(probabilities[0][i]) for i in range(10)}
56
  except Exception as e:
57
  print(f"Error in predict function: {e}")
 
 
58
  return {"error": str(e)}
59
 
60
  # Create the Gradio interface
 
39
  # Prediction function
40
 
41
 
42
+
43
+ def predict(image):
44
  try:
45
+ # The input image is already a 2D numpy array (grayscale)
46
+ # Ensure it's the right size and normalize it
47
+ if image.shape != (28, 28):
48
+ pil_image = Image.fromarray(image.squeeze().astype('uint8'))
49
+ pil_image = pil_image.resize((28, 28))
50
+ image = np.array(pil_image)
51
+
52
+ # Convert to tensor and add batch and channel dimensions
53
+ tensor_image = torch.tensor(image, dtype=torch.float32).unsqueeze(0).unsqueeze(0)
54
 
55
+ # Normalize the image
56
+ tensor_image = tensor_image / 255.0 # Scale to [0, 1]
57
+ tensor_image = (tensor_image - 0.5) / 0.5 # Normalize to [-1, 1]
58
 
59
  with torch.no_grad():
60
+ output = model(tensor_image)
61
  probabilities = nn.Softmax(dim=1)(output)
62
 
63
  # Return the probabilities as a dictionary
64
  return {str(i): float(probabilities[0][i]) for i in range(10)}
65
  except Exception as e:
66
  print(f"Error in predict function: {e}")
67
+ import traceback
68
+ traceback.print_exc()
69
  return {"error": str(e)}
70
 
71
  # Create the Gradio interface