Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
from PIL import Image
|
4 |
+
import tensorflow as tf
|
5 |
+
from transformers import ViTFeatureExtractor
|
6 |
+
from huggingface_hub import from_pretrained_keras
|
7 |
+
|
8 |
+
PRETRAIN_CHECKPOINT = "google/vit-base-patch16-224-in21k"
|
9 |
+
feature_extractor = ViTFeatureExtractor.from_pretrained(PRETRAIN_CHECKPOINT)
|
10 |
+
|
11 |
+
MODEL_CKPT = "chansung/vit-e2e-pipeline-hf-integration@v1664863171"
|
12 |
+
MODEL = from_pretrained_keras(MODEL_CKPT)
|
13 |
+
|
14 |
+
RESOLTUION = 224
|
15 |
+
|
16 |
+
labels = []
|
17 |
+
|
18 |
+
with open(r"labels.txt", "r") as fp:
|
19 |
+
for line in fp:
|
20 |
+
labels.append(line[:-1])
|
21 |
+
|
22 |
+
def normalize_img(
|
23 |
+
img, mean=feature_extractor.image_mean, std=feature_extractor.image_std
|
24 |
+
):
|
25 |
+
img = img / 255
|
26 |
+
mean = tf.constant(mean)
|
27 |
+
std = tf.constant(std)
|
28 |
+
return (img - mean) / std
|
29 |
+
|
30 |
+
def preprocess_input(image: Image) -> tf.Tensor:
|
31 |
+
image = np.array(image)
|
32 |
+
image = tf.convert_to_tensor(image)
|
33 |
+
|
34 |
+
image = tf.image.resize(image, (RESOLTUION, RESOLTUION))
|
35 |
+
image = normalize_img(image)
|
36 |
+
|
37 |
+
image = tf.transpose(
|
38 |
+
image, (2, 0, 1)
|
39 |
+
) # Since HF models are channel-first.
|
40 |
+
|
41 |
+
return {
|
42 |
+
"pixel_values": tf.expand_dims(image, 0)
|
43 |
+
}
|
44 |
+
|
45 |
+
def get_predictions(image: Image) -> tf.Tensor:
|
46 |
+
preprocessed_image = preprocess_input(image)
|
47 |
+
prediction = MODEL.predict(preprocessed_image)
|
48 |
+
probs = tf.nn.softmax(prediction['logits'], axis=1)
|
49 |
+
|
50 |
+
confidences = {labels[i]: float(probs[0][i]) for i in range(3)}
|
51 |
+
return confidences
|
52 |
+
|
53 |
+
title = "Simple demo for a Image Classification of the Beans Dataset with HF ViT model"
|
54 |
+
|
55 |
+
demo = gr.Interface(
|
56 |
+
get_predictions,
|
57 |
+
gr.inputs.Image(type="pil"),
|
58 |
+
gr.outputs.Label(num_top_classes=3),
|
59 |
+
allow_flagging="never",
|
60 |
+
title=title,
|
61 |
+
)
|
62 |
+
|
63 |
+
demo.launch(debug=True)
|