File size: 1,468 Bytes
6ad9d8e
 
 
 
 
 
 
 
6aca538
 
6ad9d8e
 
 
 
 
6aca538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ad9d8e
 
 
6aca538
 
 
6ad9d8e
6aca538
6ad9d8e
6aca538
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import json

import gradio as gr
import tensorflow as tf
import tensorflow.keras as keras
from gradio import inputs, outputs

SIZE = 256
DEVICE = "/cpu:0"


with open("./tags.json", "rt", encoding="utf-8") as f:
    tags = json.load(f)


with tf.device(DEVICE):
    base_model = keras.applications.resnet.ResNet50(
        include_top=False, weights=None, input_shape=(SIZE, SIZE, 3)
    )
    model = keras.Sequential(
        [
            base_model,
            keras.layers.Conv2D(filters=len(tags), kernel_size=(1, 1), padding="same"),
            keras.layers.BatchNormalization(epsilon=1.001e-5),
            keras.layers.GlobalAveragePooling2D(name="avg_pool"),
            keras.layers.Activation("sigmoid"),
        ]
    )
    model.load_weights("tf_model.h5")


def predict(img, hide: float):
    with tf.device(DEVICE):
        img = tf.image.resize_with_pad(img, SIZE, SIZE)
        img = tf.image.per_image_standardization(img)
        data = tf.expand_dims(img, 0)
        out, *_ = model(data)
    labels = {tag: float(out[i].numpy()) for i, tag in enumerate(tags)}
    return {k: v for k, v in labels.items() if v >= hide}


image = inputs.Image(label="Upload your image here!")
hide_threshold = inputs.Slider(
    label="Hide confidence lower than", default=0.5, maximum=1, minimum=0
)

labels = outputs.Label(label="Tags", type="confidences")

interface = gr.Interface(predict, inputs=[image, hide_threshold], outputs=[labels])
interface.launch()