Spaces:
Running
Running
update
Browse files- .gitignore +164 -0
- app.py +28 -0
- requirements.txt +3 -0
- utils.py +128 -0
.gitignore
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
|
6 |
+
# C extensions
|
7 |
+
*.so
|
8 |
+
|
9 |
+
# Distribution / packaging
|
10 |
+
.Python
|
11 |
+
build/
|
12 |
+
develop-eggs/
|
13 |
+
dist/
|
14 |
+
downloads/
|
15 |
+
eggs/
|
16 |
+
.eggs/
|
17 |
+
lib/
|
18 |
+
lib64/
|
19 |
+
parts/
|
20 |
+
sdist/
|
21 |
+
var/
|
22 |
+
wheels/
|
23 |
+
share/python-wheels/
|
24 |
+
*.egg-info/
|
25 |
+
.installed.cfg
|
26 |
+
*.egg
|
27 |
+
MANIFEST
|
28 |
+
|
29 |
+
# PyInstaller
|
30 |
+
# Usually these files are written by a python script from a template
|
31 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
32 |
+
*.manifest
|
33 |
+
*.spec
|
34 |
+
|
35 |
+
# Installer logs
|
36 |
+
pip-log.txt
|
37 |
+
pip-delete-this-directory.txt
|
38 |
+
|
39 |
+
# Unit test / coverage reports
|
40 |
+
htmlcov/
|
41 |
+
.tox/
|
42 |
+
.nox/
|
43 |
+
.coverage
|
44 |
+
.coverage.*
|
45 |
+
.cache
|
46 |
+
nosetests.xml
|
47 |
+
coverage.xml
|
48 |
+
*.cover
|
49 |
+
*.py,cover
|
50 |
+
.hypothesis/
|
51 |
+
.pytest_cache/
|
52 |
+
cover/
|
53 |
+
|
54 |
+
# Translations
|
55 |
+
*.mo
|
56 |
+
*.pot
|
57 |
+
|
58 |
+
# Django stuff:
|
59 |
+
*.log
|
60 |
+
local_settings.py
|
61 |
+
db.sqlite3
|
62 |
+
db.sqlite3-journal
|
63 |
+
|
64 |
+
# Flask stuff:
|
65 |
+
instance/
|
66 |
+
.webassets-cache
|
67 |
+
|
68 |
+
# Scrapy stuff:
|
69 |
+
.scrapy
|
70 |
+
|
71 |
+
# Sphinx documentation
|
72 |
+
docs/_build/
|
73 |
+
|
74 |
+
# PyBuilder
|
75 |
+
.pybuilder/
|
76 |
+
target/
|
77 |
+
|
78 |
+
# Jupyter Notebook
|
79 |
+
.ipynb_checkpoints
|
80 |
+
|
81 |
+
# IPython
|
82 |
+
profile_default/
|
83 |
+
ipython_config.py
|
84 |
+
|
85 |
+
# pyenv
|
86 |
+
# For a library or package, you might want to ignore these files since the code is
|
87 |
+
# intended to run in multiple environments; otherwise, check them in:
|
88 |
+
# .python-version
|
89 |
+
|
90 |
+
# pipenv
|
91 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
92 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
93 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
94 |
+
# install all needed dependencies.
|
95 |
+
#Pipfile.lock
|
96 |
+
|
97 |
+
# poetry
|
98 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
99 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
100 |
+
# commonly ignored for libraries.
|
101 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
102 |
+
#poetry.lock
|
103 |
+
|
104 |
+
# pdm
|
105 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
106 |
+
#pdm.lock
|
107 |
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
108 |
+
# in version control.
|
109 |
+
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
110 |
+
.pdm.toml
|
111 |
+
.pdm-python
|
112 |
+
.pdm-build/
|
113 |
+
|
114 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
115 |
+
__pypackages__/
|
116 |
+
|
117 |
+
# Celery stuff
|
118 |
+
celerybeat-schedule
|
119 |
+
celerybeat.pid
|
120 |
+
|
121 |
+
# SageMath parsed files
|
122 |
+
*.sage.py
|
123 |
+
|
124 |
+
# Environments
|
125 |
+
.env
|
126 |
+
.venv
|
127 |
+
env/
|
128 |
+
venv/
|
129 |
+
ENV/
|
130 |
+
env.bak/
|
131 |
+
venv.bak/
|
132 |
+
|
133 |
+
# Spyder project settings
|
134 |
+
.spyderproject
|
135 |
+
.spyproject
|
136 |
+
|
137 |
+
# Rope project settings
|
138 |
+
.ropeproject
|
139 |
+
|
140 |
+
# mkdocs documentation
|
141 |
+
/site
|
142 |
+
|
143 |
+
# mypy
|
144 |
+
.mypy_cache/
|
145 |
+
.dmypy.json
|
146 |
+
dmypy.json
|
147 |
+
|
148 |
+
# Pyre type checker
|
149 |
+
.pyre/
|
150 |
+
|
151 |
+
# pytype static type analyzer
|
152 |
+
.pytype/
|
153 |
+
|
154 |
+
# Cython debug symbols
|
155 |
+
cython_debug/
|
156 |
+
|
157 |
+
# PyCharm
|
158 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
159 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
160 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
161 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
162 |
+
#.idea/
|
163 |
+
|
164 |
+
tmp.py
|
app.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import gradio as gr
|
3 |
+
import os
|
4 |
+
import spaces
|
5 |
+
from tqdm import tqdm
|
6 |
+
from PIL import Image
|
7 |
+
from utils import WaifuScorer
|
8 |
+
|
9 |
+
SCORER = WaifuScorer(
|
10 |
+
device='cuda',
|
11 |
+
verbose=True,
|
12 |
+
)
|
13 |
+
|
14 |
+
|
15 |
+
@spaces.GPU
|
16 |
+
def score_image(image: Image.Image) -> float:
|
17 |
+
return SCORER([image])[0]
|
18 |
+
|
19 |
+
|
20 |
+
demo = gr.Interface(
|
21 |
+
fn=score_image,
|
22 |
+
inputs=gr.Image(type='pil', label='Image'),
|
23 |
+
outputs=gr.Number(label='Score', precision=2),
|
24 |
+
title='Waifu Scorer V3',
|
25 |
+
description='''Score ranges from 0 to 10, higher is better.
|
26 |
+
[Github](https://github.com/Eugeoter/waifu-scorer) | [Model](https://huggingface.co/Eugeoter/waifu-scorer-v3) | [Inspiration](https://github.com/christophschuhmann/improved-aesthetic-predictor)''',
|
27 |
+
)
|
28 |
+
demo.queue().launch()
|
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
safetensors
|
3 |
+
pytorch-lightning
|
utils.py
ADDED
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import pytorch_lightning as pl
|
5 |
+
from typing import List, Union
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
WS_REPOS = ["Eugeoter/waifu-scorer-v3"]
|
9 |
+
|
10 |
+
|
11 |
+
class MLP(pl.LightningModule):
|
12 |
+
def __init__(self, input_size, xcol='emb', ycol='avg_rating', batch_norm=True):
|
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, 2048),
|
19 |
+
nn.ReLU(),
|
20 |
+
nn.BatchNorm1d(2048) if batch_norm else nn.Identity(),
|
21 |
+
nn.Dropout(0.3),
|
22 |
+
nn.Linear(2048, 512),
|
23 |
+
nn.ReLU(),
|
24 |
+
nn.BatchNorm1d(512) if batch_norm else nn.Identity(),
|
25 |
+
nn.Dropout(0.3),
|
26 |
+
nn.Linear(512, 256),
|
27 |
+
nn.ReLU(),
|
28 |
+
nn.BatchNorm1d(256) if batch_norm else nn.Identity(),
|
29 |
+
nn.Dropout(0.2),
|
30 |
+
nn.Linear(256, 128),
|
31 |
+
nn.ReLU(),
|
32 |
+
nn.BatchNorm1d(128) if batch_norm else nn.Identity(),
|
33 |
+
nn.Dropout(0.1),
|
34 |
+
nn.Linear(128, 32),
|
35 |
+
nn.ReLU(),
|
36 |
+
nn.Linear(32, 1)
|
37 |
+
)
|
38 |
+
|
39 |
+
def forward(self, x):
|
40 |
+
return self.layers(x)
|
41 |
+
|
42 |
+
|
43 |
+
class WaifuScorer(object):
|
44 |
+
def __init__(self, model_path=None, device='cuda', cache_dir=None, verbose=False):
|
45 |
+
self.verbose = verbose
|
46 |
+
if model_path is None:
|
47 |
+
model_path = repo2path(WS_REPOS[0])
|
48 |
+
if self.verbose:
|
49 |
+
print(f"model path not set, switch to default: `{model_path}`")
|
50 |
+
if not os.path.isfile(model_path):
|
51 |
+
model_path = download_from_url(model_path, cache_dir=cache_dir)
|
52 |
+
|
53 |
+
print(f"loading pretrained model from `{model_path}`")
|
54 |
+
self.mlp = load_model(model_path, input_size=768, device=device)
|
55 |
+
self.model2, self.preprocess = load_clip_models("ViT-L/14", device=device)
|
56 |
+
self.device = self.mlp.device
|
57 |
+
self.dtype = self.mlp.dtype
|
58 |
+
self.mlp.eval()
|
59 |
+
|
60 |
+
@torch.no_grad()
|
61 |
+
def __call__(self, images: List[Image.Image]) -> Union[List[float], float]:
|
62 |
+
if isinstance(images, Image.Image):
|
63 |
+
images = [images]
|
64 |
+
n = len(images)
|
65 |
+
if n == 1:
|
66 |
+
images = images*2 # batch norm
|
67 |
+
images = encode_images(images, self.model2, self.preprocess, device=self.device).to(device=self.device, dtype=self.dtype)
|
68 |
+
predictions = self.mlp(images)
|
69 |
+
scores = predictions.clamp(0, 10).cpu().numpy().reshape(-1).tolist()
|
70 |
+
# if n == 1:
|
71 |
+
# scores = scores[0]
|
72 |
+
return scores
|
73 |
+
|
74 |
+
|
75 |
+
def repo2path(model_repo_and_path: str):
|
76 |
+
if os.path.isfile(model_repo_and_path):
|
77 |
+
model_path = model_repo_and_path
|
78 |
+
elif os.path.isdir(model_repo_and_path):
|
79 |
+
model_path = os.path.join(model_repo_and_path, "model.pth")
|
80 |
+
elif model_repo_and_path in WS_REPOS:
|
81 |
+
model_path = model_repo_and_path + '/model.pth'
|
82 |
+
else:
|
83 |
+
raise ValueError(f"Invalid model_repo_and_path: {model_repo_and_path}")
|
84 |
+
return model_path
|
85 |
+
|
86 |
+
|
87 |
+
def download_from_url(url, cache_dir=None, verbose=True):
|
88 |
+
from huggingface_hub import hf_hub_download
|
89 |
+
split = url.split("/")
|
90 |
+
username, repo_id, model_name = split[-3], split[-2], split[-1]
|
91 |
+
# if verbose:
|
92 |
+
# print(f"[download_from_url]: {username}/{repo_id}/{model_name}")
|
93 |
+
model_path = hf_hub_download(f"{username}/{repo_id}", model_name, cache_dir=cache_dir)
|
94 |
+
return model_path
|
95 |
+
|
96 |
+
|
97 |
+
def load_clip_models(name: str = "ViT-L/14", device='cuda'):
|
98 |
+
import clip
|
99 |
+
model2, preprocess = clip.load(name, device=device) # RN50x64
|
100 |
+
return model2, preprocess
|
101 |
+
|
102 |
+
|
103 |
+
def load_model(model_path: str = None, input_size=768, device: str = 'cuda', dtype=None):
|
104 |
+
model = MLP(input_size=input_size)
|
105 |
+
if model_path:
|
106 |
+
s = torch.load(model_path, map_location=device)
|
107 |
+
model.load_state_dict(s)
|
108 |
+
model.to(device)
|
109 |
+
if dtype:
|
110 |
+
model = model.to(dtype=dtype)
|
111 |
+
return model
|
112 |
+
|
113 |
+
|
114 |
+
def normalized(a: torch.Tensor, order=2, dim=-1):
|
115 |
+
l2 = a.norm(order, dim, keepdim=True)
|
116 |
+
l2[l2 == 0] = 1
|
117 |
+
return a / l2
|
118 |
+
|
119 |
+
|
120 |
+
@torch.no_grad()
|
121 |
+
def encode_images(images: List[Image.Image], model2, preprocess, device='cuda') -> torch.Tensor:
|
122 |
+
if isinstance(images, Image.Image):
|
123 |
+
images = [images]
|
124 |
+
image_tensors = [preprocess(img).unsqueeze(0) for img in images]
|
125 |
+
image_batch = torch.cat(image_tensors).to(device)
|
126 |
+
image_features = model2.encode_image(image_batch)
|
127 |
+
im_emb_arr = normalized(image_features).cpu().float()
|
128 |
+
return im_emb_arr
|