seedmanc Geonmo commited on
Commit
1d50f06
·
0 Parent(s):

Duplicate from Geonmo/laion-aesthetic-predictor

Browse files

Co-authored-by: Geonmo Gu <[email protected]>

Files changed (8) hide show
  1. .gitattributes +33 -0
  2. README.md +14 -0
  3. app.py +133 -0
  4. example1.jpg +0 -0
  5. example2.jpg +0 -0
  6. example3.jpg +0 -0
  7. requirements.txt +6 -0
  8. sac+logos+ava1-l14-linearMSE.pth +3 -0
.gitattributes ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
11
+ *.model filter=lfs diff=lfs merge=lfs -text
12
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
13
+ *.npy filter=lfs diff=lfs merge=lfs -text
14
+ *.npz filter=lfs diff=lfs merge=lfs -text
15
+ *.onnx filter=lfs diff=lfs merge=lfs -text
16
+ *.ot filter=lfs diff=lfs merge=lfs -text
17
+ *.parquet filter=lfs diff=lfs merge=lfs -text
18
+ *.pb filter=lfs diff=lfs merge=lfs -text
19
+ *.pickle filter=lfs diff=lfs merge=lfs -text
20
+ *.pkl filter=lfs diff=lfs merge=lfs -text
21
+ *.pt filter=lfs diff=lfs merge=lfs -text
22
+ *.pth filter=lfs diff=lfs merge=lfs -text
23
+ *.rar filter=lfs diff=lfs merge=lfs -text
24
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
25
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
26
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
27
+ *.tflite filter=lfs diff=lfs merge=lfs -text
28
+ *.tgz filter=lfs diff=lfs merge=lfs -text
29
+ *.wasm filter=lfs diff=lfs merge=lfs -text
30
+ *.xz filter=lfs diff=lfs merge=lfs -text
31
+ *.zip filter=lfs diff=lfs merge=lfs -text
32
+ *.zst filter=lfs diff=lfs merge=lfs -text
33
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Laion Aesthetic Predictor
3
+ emoji: 🎨
4
+ colorFrom: red
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 3.6
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ duplicated_from: Geonmo/laion-aesthetic-predictor
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import torch
4
+ import pytorch_lightning as pl
5
+ import torch.nn as nn
6
+ import clip
7
+ from PIL import Image, ImageFile
8
+ import gradio as gr
9
+
10
+ # if you changed the MLP architecture during training, change it also here:
11
+ class MLP(pl.LightningModule):
12
+ def __init__(self, input_size, xcol='emb', ycol='avg_rating'):
13
+ super().__init__()
14
+ self.input_size = input_size
15
+ self.xcol = xcol
16
+ self.ycol = ycol
17
+ self.layers = nn.Sequential(
18
+ nn.Linear(self.input_size, 1024),
19
+ #nn.ReLU(),
20
+ nn.Dropout(0.2),
21
+ nn.Linear(1024, 128),
22
+ #nn.ReLU(),
23
+ nn.Dropout(0.2),
24
+ nn.Linear(128, 64),
25
+ #nn.ReLU(),
26
+ nn.Dropout(0.1),
27
+
28
+ nn.Linear(64, 16),
29
+ #nn.ReLU(),
30
+
31
+ nn.Linear(16, 1)
32
+ )
33
+
34
+ def forward(self, x):
35
+ return self.layers(x)
36
+
37
+ def training_step(self, batch, batch_idx):
38
+ x = batch[self.xcol]
39
+ y = batch[self.ycol].reshape(-1, 1)
40
+ x_hat = self.layers(x)
41
+ loss = F.mse_loss(x_hat, y)
42
+ return loss
43
+
44
+ def validation_step(self, batch, batch_idx):
45
+ x = batch[self.xcol]
46
+ y = batch[self.ycol].reshape(-1, 1)
47
+ x_hat = self.layers(x)
48
+ loss = F.mse_loss(x_hat, y)
49
+ return loss
50
+
51
+ def configure_optimizers(self):
52
+ optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)
53
+ return optimizer
54
+
55
+ def normalized(a, axis=-1, order=2):
56
+ import numpy as np # pylint: disable=import-outside-toplevel
57
+
58
+ l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
59
+ l2[l2 == 0] = 1
60
+ return a / np.expand_dims(l2, axis)
61
+
62
+ def load_models():
63
+ model = MLP(768)
64
+
65
+ device = "cuda" if torch.cuda.is_available() else "cpu"
66
+
67
+ s = torch.load("sac+logos+ava1-l14-linearMSE.pth", map_location=device)
68
+
69
+ model.load_state_dict(s)
70
+ model.to(device)
71
+ model.eval()
72
+
73
+ model2, preprocess = clip.load("ViT-L/14", device=device)
74
+
75
+ model_dict = {}
76
+ model_dict['classifier'] = model
77
+ model_dict['clip_model'] = model2
78
+ model_dict['clip_preprocess'] = preprocess
79
+ model_dict['device'] = device
80
+
81
+ return model_dict
82
+
83
+ def predict(image):
84
+ image_input = model_dict['clip_preprocess'](image).unsqueeze(0).to(model_dict['device'])
85
+ with torch.no_grad():
86
+ image_features = model_dict['clip_model'].encode_image(image_input)
87
+ if model_dict['device'] == 'cuda':
88
+ im_emb_arr = normalized(image_features.detach().cpu().numpy())
89
+ im_emb = torch.from_numpy(im_emb_arr).to(model_dict['device']).type(torch.cuda.FloatTensor)
90
+ else:
91
+ im_emb_arr = normalized(image_features.detach().numpy())
92
+ im_emb = torch.from_numpy(im_emb_arr).to(model_dict['device']).type(torch.FloatTensor)
93
+
94
+ prediction = model_dict['classifier'](im_emb)
95
+ score = prediction.item()
96
+
97
+ return {'aesthetic score': score}
98
+
99
+ if __name__ == '__main__':
100
+ print('\tinit models')
101
+
102
+ global model_dict
103
+
104
+ model_dict = load_models()
105
+
106
+ inputs = [gr.inputs.Image(type='pil', label='Image')]
107
+
108
+ outputs = gr.outputs.JSON()
109
+
110
+ title = 'image aesthetic predictor'
111
+
112
+ examples = ['example1.jpg', 'example2.jpg', 'example3.jpg']
113
+
114
+ description = """
115
+ # Image Aesthetic Predictor Demo
116
+ This model (Image Aesthetic Predictor) is trained by LAION Team. See [https://github.com/christophschuhmann/improved-aesthetic-predictor](https://github.com/christophschuhmann/improved-aesthetic-predictor)
117
+ 1. This model is desgined by adding five MLP layers on top of (frozen) CLIP ViT-L/14 and only the MLP layers are fine-tuned with a lot of images by a regression loss term such as MSE and MAE.
118
+ 2. Output is bounded from 0 to 10. The higher the better.
119
+ """
120
+
121
+ article = "<p style='text-align: center'><a href='https://laion.ai/blog/laion-aesthetics/'>LAION aesthetics blog post</a></p>"
122
+
123
+ with gr.Blocks() as demo:
124
+ gr.Markdown(description)
125
+ with gr.Row():
126
+ with gr.Column():
127
+ image_input = gr.Image(type='pil', label='Input image')
128
+ submit_button = gr.Button('Submit')
129
+ json_output = gr.JSON(label='Output')
130
+ submit_button.click(predict, inputs=image_input, outputs=json_output)
131
+ gr.Examples(examples=examples, inputs=image_input)
132
+ gr.HTML(article)
133
+ demo.launch()
example1.jpg ADDED
example2.jpg ADDED
example3.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ftfy
2
+ regex
3
+ git+https://github.com/openai/CLIP.git
4
+ gradio
5
+ torch
6
+ pytorch-lightning
sac+logos+ava1-l14-linearMSE.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21dd590f3ccdc646f0d53120778b296013b096a035a2718c9cb0d511bff0f1e0
3
+ size 3714759