dgith commited on
Commit
6eff061
Β·
verified Β·
1 Parent(s): 1e95cbb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -73
app.py CHANGED
@@ -1,76 +1,77 @@
1
- # app.py - Gradio interface that loads pre-trained MNIST model
2
 
3
  import gradio as gr
4
  import numpy as np
5
  import tensorflow as tf
6
- from PIL import Image
7
- import cv2
8
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- # Ensure model path exists
11
- MODEL_PATH = "model/mnist_model.h5"
12
- if not os.path.exists(MODEL_PATH):
13
- raise FileNotFoundError(f"Model file not found at {MODEL_PATH}. Upload model/mnist_model.h5")
14
 
15
- print("Loading trained MNIST model...")
16
- model = tf.keras.models.load_model(MODEL_PATH)
17
- print("βœ… Model loaded successfully!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  def preprocess_image(image):
20
- """Convert input image to MNIST-compatible format"""
21
  if image is None:
22
  return None
23
-
24
- # Convert from RGB to grayscale
25
- if len(image.shape) == 3:
26
- gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
27
- else:
28
- gray = image.copy()
29
-
30
- # Resize to 28x28
31
  resized = cv2.resize(gray, (28, 28), interpolation=cv2.INTER_AREA)
32
-
33
- # Invert if background is dark (most drawings are white on black)
34
- if resized.mean() < 128:
35
  resized = 255 - resized
36
-
37
- # Normalize and reshape
38
  normalized = resized.astype('float32') / 255.0
39
  return normalized
40
 
41
  def predict_digit(image):
42
- """Predict digit from input image"""
43
  processed = preprocess_image(image)
44
  if processed is None:
45
  return {str(i): 0.0 for i in range(10)}
46
-
47
- # Add batch dimension
48
  input_tensor = np.expand_dims(processed, axis=0)
49
-
50
- # Predict
51
- predictions = model.predict(input_tensor, verbose=0)[0]
52
-
53
- # Return dict for Gradio BarPlot
54
- return {str(i): float(predictions[i]) for i in range(10)}
55
-
56
- # Custom CSS to make it look cleaner (like shadcn style)
57
- custom_css = """
58
- .gradio-container {
59
- font-family: 'Inter', sans-serif;
60
- }
61
- h1 {
62
- text-align: center !important;
63
- color: #1a1a1a;
64
- }
65
- .button-primary {
66
- background-color: #18181b !important;
67
- border: 1px solid #333 !important;
68
- }
69
- """
70
-
71
- with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
72
  gr.Markdown("# πŸ”’ Kilele AI Tutor: Handwritten Digit Recognition")
73
- gr.Markdown("Draw or upload a digit (0–9). Our AI will guess what it is!")
74
 
75
  with gr.Row():
76
  with gr.Column():
@@ -79,35 +80,15 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
79
  image_mode="L",
80
  canvas_size=(200, 200),
81
  brush=gr.Brush(default_size=20),
82
- type="numpy",
83
- height=300
84
  )
85
  upload_btn = gr.UploadButton("πŸ“ Upload Image", file_types=["image"])
86
  clear_btn = gr.Button("🧹 Clear Canvas")
87
 
88
  with gr.Column():
89
  output_label = gr.Label(label="Prediction", num_top_classes=1)
90
- output_bars = gr.BarPlot(
91
- label="Confidence Scores",
92
- x_title="Digit",
93
- y_title="Probability",
94
- width=400
95
- )
96
 
97
- # Examples
98
- gr.Examples(
99
- examples=[
100
- ["https://huggingface.co/datasets/Nbain/mnist_examples/resolve/main/one.png"],
101
- ["https://huggingface.co/datasets/Nbain/mnist_examples/resolve/main/seven.png"],
102
- ["https://huggingface.co/datasets/Nbain/mnist_examples/resolve/main/two.png"]
103
- ],
104
- inputs=sketchpad,
105
- outputs=[output_label, output_bars],
106
- fn=predict_digit,
107
- cache_examples=True
108
- )
109
-
110
- # Events
111
  sketchpad.change(fn=predict_digit, inputs=sketchpad, outputs=[output_label, output_bars])
112
  upload_btn.upload(fn=lambda img: predict_digit(img), inputs=upload_btn, outputs=[output_label, output_bars])
113
  clear_btn.click(fn=lambda: None, inputs=None, outputs=sketchpad)
 
1
+ # app.py - Trains MNIST on first launch, then reuses model
2
 
3
  import gradio as gr
4
  import numpy as np
5
  import tensorflow as tf
 
 
6
  import os
7
+ import cv2
8
+
9
+ # Define model path
10
+ MODEL_DIR = "model"
11
+ MODEL_PATH = os.path.join(MODEL_DIR, "mnist_model.h5")
12
+
13
+ # Create model directory if not exists
14
+ os.makedirs(MODEL_DIR, exist_ok=True)
15
+
16
+ print("Checking for existing model...")
17
+
18
+ if os.path.exists(MODEL_PATH):
19
+ print("βœ… Loading pre-trained model...")
20
+ model = tf.keras.models.load_model(MODEL_PATH)
21
+ else:
22
+ print("❌ Model not found. Training new model...")
23
 
24
+ # Load and preprocess data
25
+ (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
26
+ x_train = x_train.astype('float32') / 255.0
27
+ x_test = x_test.astype('float32') / 255.0
28
 
29
+ # Build model
30
+ model = tf.keras.Sequential([
31
+ tf.keras.layers.Flatten(input_shape=(28, 28)),
32
+ tf.keras.layers.Dense(128, activation='relu'),
33
+ tf.keras.layers.Dropout(0.2),
34
+ tf.keras.layers.Dense(64, activation='relu'),
35
+ tf.keras.layers.Dropout(0.1),
36
+ tf.keras.layers.Dense(10, activation='softmax')
37
+ ])
38
+
39
+ model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
40
+
41
+ # Train (fast: 5 epochs on full MNIST)
42
+ print("Starting training...")
43
+ model.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_test, y_test), verbose=1)
44
+
45
+ # Save model
46
+ model.save(MODEL_PATH)
47
+ print(f"πŸ’Ύ Model saved to {MODEL_PATH}")
48
+
49
+ # Optional: Evaluate
50
+ test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=0)
51
+ print(f"πŸŽ‰ Training complete! Test Accuracy: {test_accuracy:.4f}")
52
 
53
  def preprocess_image(image):
 
54
  if image is None:
55
  return None
56
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) if len(image.shape)==3 else image
 
 
 
 
 
 
 
57
  resized = cv2.resize(gray, (28, 28), interpolation=cv2.INTER_AREA)
58
+ if resized.mean() < 128: # invert if dark background
 
 
59
  resized = 255 - resized
 
 
60
  normalized = resized.astype('float32') / 255.0
61
  return normalized
62
 
63
  def predict_digit(image):
 
64
  processed = preprocess_image(image)
65
  if processed is None:
66
  return {str(i): 0.0 for i in range(10)}
 
 
67
  input_tensor = np.expand_dims(processed, axis=0)
68
+ preds = model.predict(input_tensor, verbose=0)[0]
69
+ return {str(i): float(preds[i]) for i in range(10)}
70
+
71
+ # Gradio UI
72
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  gr.Markdown("# πŸ”’ Kilele AI Tutor: Handwritten Digit Recognition")
74
+ gr.Markdown("Draw or upload a digit (0–9). Our AI will classify it!")
75
 
76
  with gr.Row():
77
  with gr.Column():
 
80
  image_mode="L",
81
  canvas_size=(200, 200),
82
  brush=gr.Brush(default_size=20),
83
+ type="numpy"
 
84
  )
85
  upload_btn = gr.UploadButton("πŸ“ Upload Image", file_types=["image"])
86
  clear_btn = gr.Button("🧹 Clear Canvas")
87
 
88
  with gr.Column():
89
  output_label = gr.Label(label="Prediction", num_top_classes=1)
90
+ output_bars = gr.BarPlot(label="Confidence Scores", x_title="Digit", y_title="Probability")
 
 
 
 
 
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  sketchpad.change(fn=predict_digit, inputs=sketchpad, outputs=[output_label, output_bars])
93
  upload_btn.upload(fn=lambda img: predict_digit(img), inputs=upload_btn, outputs=[output_label, output_bars])
94
  clear_btn.click(fn=lambda: None, inputs=None, outputs=sketchpad)