mayhug commited on
Commit
26d2f56
·
1 Parent(s): 7db75cf

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ import gradio
4
+ import torch
5
+ from gradio import inputs, outputs
6
+ from PIL import Image
7
+ from torchvision import transforms
8
+
9
+ model = torch.hub.load("RF5/danbooru-pretrained", "resnet50")
10
+ model.eval()
11
+
12
+ with open("./tags.json", "rt", encoding="utf-8") as f:
13
+ tags = json.load(f)
14
+
15
+
16
+ def main(input_image: Image.Image, threshold: float):
17
+ preprocess = transforms.Compose(
18
+ [
19
+ transforms.Resize(360),
20
+ transforms.ToTensor(),
21
+ transforms.Normalize(
22
+ mean=[0.7137, 0.6628, 0.6519], std=[0.2970, 0.3017, 0.2979]
23
+ ),
24
+ ]
25
+ )
26
+ input_tensor = preprocess(input_image)
27
+ input_batch = input_tensor.unsqueeze(
28
+ 0
29
+ ) # create a mini-batch as expected by the model
30
+
31
+ if torch.cuda.is_available():
32
+ input_batch = input_batch.to("cuda")
33
+ model.to("cuda")
34
+
35
+ with torch.no_grad():
36
+ output, *_ = model(input_batch)
37
+
38
+ probs = torch.sigmoid(output)
39
+
40
+ results = probs[probs > threshold]
41
+ inds = probs.argsort(descending=True)
42
+ tag_confidences = {}
43
+ for index in inds[0 : len(results)]:
44
+ tag_confidences[tags[index]] = float(probs[index].cpu().numpy())
45
+ return tag_confidences
46
+
47
+
48
+ image = inputs.Image(label="Upload your image here!", type="pil")
49
+ threshold = inputs.Slider(
50
+ label="Hide images confidence under", maximum=1, minimum=0, default=0.2
51
+ )
52
+
53
+ labels = outputs.Label(type="confidence")
54
+
55
+ gradio.Interface(main, inputs=[image, threshold], outputs=[labels])