Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,28 +1,55 @@
|
|
| 1 |
import tensorflow as tf
|
| 2 |
import gradio as gr
|
| 3 |
import numpy as np
|
|
|
|
| 4 |
|
| 5 |
-
# Load
|
| 6 |
model = tf.keras.models.load_model('TP_MNIST_CNN_model.h5')
|
| 7 |
|
| 8 |
-
def
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
|
|
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
|
|
|
| 18 |
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import tensorflow as tf
|
| 2 |
import gradio as gr
|
| 3 |
import numpy as np
|
| 4 |
+
import cv2
|
| 5 |
|
| 6 |
+
# Load model
|
| 7 |
model = tf.keras.models.load_model('TP_MNIST_CNN_model.h5')
|
| 8 |
|
| 9 |
+
def preprocess_and_predict(input_data):
|
| 10 |
+
if input_data is None:
|
| 11 |
+
return None
|
| 12 |
+
|
| 13 |
+
# Gradio 4.x Sketchpad returns a dict usually: {'composite': array, 'layers': [...]}
|
| 14 |
+
# We take the composite image
|
| 15 |
+
if isinstance(input_data, dict):
|
| 16 |
+
image = input_data['composite']
|
| 17 |
+
else:
|
| 18 |
+
image = input_data
|
| 19 |
|
| 20 |
+
# 1. Resize to MNIST standard (28x28)
|
| 21 |
+
# Interpolation AREA is better for shrinking images without losing thin lines
|
| 22 |
+
image = cv2.resize(image, (28, 28), interpolation=cv2.INTER_AREA)
|
| 23 |
|
| 24 |
+
# 2. Convert to Grayscale (if RGB/RGBA)
|
| 25 |
+
if len(image.shape) == 3:
|
| 26 |
+
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
| 27 |
|
| 28 |
+
# 3. Normalize & Invert Logic
|
| 29 |
+
# MNIST is White digits on Black background.
|
| 30 |
+
# If user draws Black on White, we must invert.
|
| 31 |
+
# Check mean pixel intensity: if high (>127), background is likely white.
|
| 32 |
+
if np.mean(image) > 127:
|
| 33 |
+
image = 255 - image
|
| 34 |
+
|
| 35 |
+
# 4. Normalize 0-1
|
| 36 |
+
image = image / 255.0
|
| 37 |
|
| 38 |
+
# 5. Reshape for Model (Batch, Height, Width, Channels)
|
| 39 |
+
image = image.reshape(1, 28, 28, 1)
|
| 40 |
+
|
| 41 |
+
# Prediction
|
| 42 |
+
predictions = model.predict(image, verbose=0)
|
| 43 |
+
return int(np.argmax(predictions))
|
| 44 |
+
|
| 45 |
+
# Modern Gradio 4 Interface
|
| 46 |
+
iface = gr.Interface(
|
| 47 |
+
fn=preprocess_and_predict,
|
| 48 |
+
inputs=gr.Sketchpad(label="Dessinez un chiffre", type="numpy"),
|
| 49 |
+
outputs="label",
|
| 50 |
+
title="MNIST Digit Recognition",
|
| 51 |
+
description="Reconnaissance de chiffres manuscrits via CNN. Dessinez au centre.",
|
| 52 |
+
allow_flagging="never"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
iface.launch()
|