Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoFeatureExtractor, AutoModelForImageClassification, pipeline
|
2 |
+
import torch
|
3 |
+
from PIL import Image
|
4 |
+
import gradio as gr
|
5 |
+
|
6 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
7 |
+
dtype = torch.float16
|
8 |
+
nsfw_pipe = pipeline("image-classification",
|
9 |
+
model= AutoModelForImageClassification.from_pretrained("carbon225/vit-base-patch16-224-hentai"),
|
10 |
+
feature_extractor=AutoFeatureExtractor.from_pretrained("carbon225/vit-base-patch16-224-hentai"),
|
11 |
+
device=device,
|
12 |
+
torch_dtype=dtype)
|
13 |
+
|
14 |
+
|
15 |
+
style_pipe = pipeline("image-classification",
|
16 |
+
model= AutoModelForImageClassification.from_pretrained("cafeai/cafe_style"),
|
17 |
+
feature_extractor=AutoFeatureExtractor.from_pretrained("cafeai/cafe_style"),
|
18 |
+
device=device,
|
19 |
+
torch_dtype=dtype)
|
20 |
+
|
21 |
+
aesthetic_pipe = pipeline("image-classification",
|
22 |
+
model= AutoModelForImageClassification.from_pretrained("cafeai/cafe_aesthetic"),
|
23 |
+
feature_extractor=AutoFeatureExtractor.from_pretrained("cafeai/cafe_aesthetic"),
|
24 |
+
device=device,
|
25 |
+
torch_dtype=dtype)
|
26 |
+
|
27 |
+
def predict(image, files=None):
|
28 |
+
print(image, files)
|
29 |
+
images_paths = [image]
|
30 |
+
if not files == None:
|
31 |
+
images_paths = list(map(lambda x: x.name, files))
|
32 |
+
pil_images = [Image.open(image_path).convert("RGB") for image_path in images_paths]
|
33 |
+
|
34 |
+
style = style_pipe(pil_images)
|
35 |
+
aesthetic = aesthetic_pipe(pil_images)
|
36 |
+
nsfw = nsfw_pipe(pil_images)
|
37 |
+
results = [ a + b + c for (a,b,c) in zip(style, aesthetic, nsfw)]
|
38 |
+
|
39 |
+
label_data = [{ row["label"]:row["score"] for row in image } for image in results]
|
40 |
+
|
41 |
+
return label_data[0], label_data
|
42 |
+
|
43 |
+
with gr.Blocks() as blocks:
|
44 |
+
with gr.Row():
|
45 |
+
with gr.Column():
|
46 |
+
image = gr.Image(label="Image to test", type="filepath")
|
47 |
+
files = gr.File(label="Multipls Images", file_types=["image"], file_count="multiple")
|
48 |
+
with gr.Column():
|
49 |
+
label = gr.Label(label="style")
|
50 |
+
results = gr.JSON(label="Results")
|
51 |
+
# gallery = gr.Gallery().style(grid=[2], height="auto")
|
52 |
+
btn = gr.Button("Run")
|
53 |
+
|
54 |
+
btn.click(fn=predict, inputs=[image, files], outputs=[label, results], api_name="inference")
|
55 |
+
|
56 |
+
blocks.queue()
|
57 |
+
blocks.launch(debug=True,inline=True)
|