zxcgqq commited on
Commit
4394cfc
1 Parent(s): afe0dfb

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ from os import listdir
4
+ from os.path import isfile, join, exists, isdir, abspath
5
+ import gradio as gr
6
+
7
+ import numpy as np
8
+ import tensorflow as tf
9
+ from tensorflow import keras
10
+ import tensorflow_hub as hub
11
+
12
+
13
+ IMAGE_DIM = 299 # required/default image dimensionality
14
+
15
+ def load_images(image_paths, image_size, verbose=True):
16
+ loaded_images = []
17
+ loaded_image_paths = []
18
+
19
+ if isdir(image_paths):
20
+ parent = abspath(image_paths)
21
+ image_paths = [join(parent, f) for f in listdir(image_paths) if isfile(join(parent, f))]
22
+ elif isfile(image_paths):
23
+ image_paths = [image_paths]
24
+
25
+ for img_path in image_paths:
26
+ try:
27
+ if verbose:
28
+ print(img_path, "size:", image_size)
29
+ image = keras.preprocessing.image.load_img(img_path, target_size=image_size)
30
+ image = keras.preprocessing.image.img_to_array(image)
31
+ image /= 255
32
+ loaded_images.append(image)
33
+ loaded_image_paths.append(img_path)
34
+ except Exception as ex:
35
+ print("Image Load Failure: ", img_path, ex)
36
+
37
+ return np.asarray(loaded_images), loaded_image_paths
38
+
39
+ def load_model(model_path):
40
+ if model_path is None or not exists(model_path):
41
+ raise ValueError("saved_model_path must be the valid directory of a saved model to load.")
42
+
43
+ model = tf.keras.models.load_model(model_path, custom_objects={'KerasLayer': hub.KerasLayer},compile=False)
44
+ return model
45
+
46
+
47
+ def classify_nd(model, nd_images, predict_args={}):
48
+ model_preds = model.predict(nd_images, **predict_args)
49
+ categories = ['drawings', 'hentai', 'neutral', 'porn', 'sexy']
50
+
51
+ probs = []
52
+ for i, single_preds in enumerate(model_preds):
53
+ single_probs = {}
54
+ for j, pred in enumerate(single_preds):
55
+ single_probs[categories[j]] = float(pred)
56
+ probs.append(single_probs)
57
+ return probs
58
+
59
+
60
+ def nsfw(image):
61
+ model = load_model("nsfw.299x299.h5")
62
+ image_preds = classify_nd(model, image)
63
+ return json.dumps(image_preds, indent=2)
64
+
65
+
66
+ demo = gr.Interface(fn=nsfw,
67
+ inputs= gr.Image(type="pil"),
68
+ outputs=["text"],
69
+ title="")
70
+ demo.launch(share=False)