|
import numpy as np |
|
import gradio as gr |
|
import tensorflow as tf |
|
|
|
|
|
title = "Welcome to your first sketch recognition app!" |
|
|
|
|
|
head = ( |
|
"<center>" |
|
"<img src='./mnist-classes.png' width=400>" |
|
"<p>The model is trained to classify numbers (from 0 to 9). " |
|
"To test it, draw your number in the space provided.</p>" |
|
"</center>" |
|
) |
|
|
|
|
|
ref = "Find the complete code [here](https://github.com/ovh/ai-training-examples/tree/main/apps/gradio/sketch-recognition)." |
|
|
|
|
|
img_size = 28 |
|
|
|
|
|
labels = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] |
|
|
|
|
|
model = tf.keras.models.load_model("./sketch_recognition_numbers_model.h5") |
|
|
|
|
|
def predict(data): |
|
|
|
img = np.reshape(data, (1, img_size, img_size, 1)) |
|
|
|
pred = model.predict(img) |
|
|
|
top_class = np.argmax |
|
|
|
top_3_classes = np.argsort(pred[0])[-3:][::-1] |
|
|
|
top_3_probs = pred[0][top_3_classes] |
|
|
|
class_names = [labels[i] for i in top_3_classes] |
|
|
|
return {class_names[i]: top_3_probs[i] for i in range(3)} |
|
|
|
|
|
label = gr.Label(num_top_classes=3) |
|
|
|
|
|
interface = gr.Interface( |
|
fn=predict, |
|
inputs=gr.Sketchpad(crop_size=(28,28), type='numpy', image_mode='L', brush=gr.Brush()), |
|
outputs=label, |
|
title=title, |
|
description=head, |
|
article=ref |
|
) |
|
interface.launch() |