JasonKishore commited on
Commit
fd5ef98
·
verified ·
1 Parent(s): 761dcea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -59
app.py CHANGED
@@ -1,59 +1,59 @@
1
- import gradio as gr
2
- import numpy as np
3
- from PIL import Image
4
- from tensorflow import keras
5
-
6
- model = keras.models.load_model("Digit.keras")
7
-
8
- def preprocess_image(img):
9
- if img is None:
10
- raise ValueError("No image provided.")
11
-
12
- # If Sketchpad returns a dict, try common keys
13
- if isinstance(img, dict):
14
- if "image" in img and img["image"] is not None:
15
- img = img["image"]
16
- elif "composite" in img and img["composite"] is not None:
17
- img = img["composite"]
18
- else:
19
- raise ValueError("No image data found in dictionary.")
20
-
21
- # If still a NumPy array, convert to PIL
22
- if isinstance(img, np.ndarray):
23
- img = Image.fromarray(img.astype("uint8"))
24
-
25
- # --- MNIST preprocessing ---
26
- img = img.convert("L").resize((28, 28))
27
- arr = np.array(img).astype("float32")
28
- if arr.mean() > 127: # invert if white background
29
- arr = 255 - arr
30
- arr = arr / 255.0
31
- return arr[np.newaxis, ..., np.newaxis] # (1,28,28,1)
32
-
33
- def predict(img):
34
- try:
35
- x = preprocess_image(img)
36
- probs = model.predict(x, verbose=0)[0]
37
- pred = int(np.argmax(probs))
38
- return str(pred), {str(i): float(probs[i]) for i in range(10)}
39
- except Exception as e:
40
- return f"Error: {e}", {}
41
-
42
-
43
- with gr.Blocks(title="MNIST Digit Classifier") as demo:
44
- gr.Markdown("## ✍️ Draw a digit (0–9)")
45
- with gr.Row():
46
- with gr.Column():
47
- canvas = gr.Sketchpad(
48
- canvas_size=(280, 280),
49
- type="pil", # <-- forces PIL, avoids dicts
50
- label="Draw a digit here"
51
- )
52
- btn = gr.Button("Predict")
53
- with gr.Column():
54
- pred_txt = gr.Textbox(label="Predicted Digit", interactive=False)
55
- probs = gr.Label(label="Class Probabilities", num_top_classes=10)
56
-
57
- btn.click(predict, inputs=canvas, outputs=[pred_txt, probs])
58
-
59
- demo.launch()
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ from PIL import Image
4
+ from tensorflow import keras
5
+
6
+ model = keras.models.load_model("Digit.keras")
7
+
8
+ def preprocess_image(img):
9
+ if img is None:
10
+ raise ValueError("No image provided.")
11
+
12
+ # If Sketchpad returns a dict, try common keys
13
+ if isinstance(img, dict):
14
+ if "image" in img and img["image"] is not None:
15
+ img = img["image"]
16
+ elif "composite" in img and img["composite"] is not None:
17
+ img = img["composite"]
18
+ else:
19
+ raise ValueError("No image data found in dictionary.")
20
+
21
+ # If still a NumPy array, convert to PIL
22
+ if isinstance(img, np.ndarray):
23
+ img = Image.fromarray(img.astype("uint8"))
24
+
25
+ # --- MNIST preprocessing ---
26
+ img = img.convert("L").resize((28, 28))
27
+ arr = np.array(img).astype("float32")
28
+ if arr.mean() > 127: # invert if white background
29
+ arr = 255 - arr
30
+ arr = arr / 255.0
31
+ return arr[np.newaxis, ..., np.newaxis] # (1,28,28,1)
32
+
33
+ def predict(img):
34
+ try:
35
+ x = preprocess_image(img)
36
+ probs = model.predict(x, verbose=0)[0]
37
+ pred = int(np.argmax(probs))
38
+ return str(pred), {str(i): float(probs[i]) for i in range(10)}
39
+ except Exception as e:
40
+ return f"Error: {e}", {}
41
+
42
+
43
+ with gr.Blocks(title="MNIST Digit Classifier") as demo:
44
+ gr.Markdown("## ✍️ Draw a digit (0–9)")
45
+ with gr.Row():
46
+ with gr.Column():
47
+ canvas = gr.Sketchpad(
48
+ canvas_size=(280, 280),
49
+ type="pil", # <-- forces PIL, avoids dicts
50
+ label="Draw a digit here"
51
+ )
52
+ btn = gr.Button("Predict")
53
+ with gr.Column():
54
+ pred_txt = gr.Textbox(label="Predicted Digit", interactive=False)
55
+ probs = gr.Label(label="Class Probabilities", num_top_classes=10)
56
+
57
+ btn.click(predict, inputs=canvas, outputs=[pred_txt, probs])
58
+
59
+ demo.launch(share=True)