Spaces:
Runtime error
Runtime error
init
Browse files- .gitignore +162 -0
- .idea/.gitignore +8 -0
- .idea/Waifu2X-Image-Scale.iml +8 -0
- .idea/deployment.xml +14 -0
- .idea/inspectionProfiles/Project_Default.xml +16 -0
- .idea/inspectionProfiles/profiles_settings.xml +6 -0
- .idea/misc.xml +4 -0
- .idea/modules.xml +8 -0
- .idea/vcs.xml +6 -0
- Waifu2x/.gitattributes +1 -0
- Waifu2x/.gitignore +4 -0
- Waifu2x/Common.py +189 -0
- Waifu2x/Dataloader.py +215 -0
- Waifu2x/Img_to_Sqlite.py +115 -0
- Waifu2x/LICENSE +674 -0
- Waifu2x/Loss.py +44 -0
- Waifu2x/Models.py +316 -0
- Waifu2x/Readme.md +167 -0
- Waifu2x/__init__.py +9 -0
- Waifu2x/magnify.py +86 -0
- Waifu2x/model_check_points/CRAN_V2/CARN_adam_checkpoint.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/CARN_model_checkpoint.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/CARN_scheduler_last_iter.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/CRAN_V2_02_28_2019.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/ReadME.md +41 -0
- Waifu2x/model_check_points/CRAN_V2/test_loss.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/test_psnr.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/test_ssim.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/train_loss.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/train_psnr.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/train_ssim.pt +3 -0
- Waifu2x/model_check_points/ReadME.md +34 -0
- Waifu2x/train.py +174 -0
- Waifu2x/utils/Img_to_H5.py +50 -0
- Waifu2x/utils/__init__.py +8 -0
- Waifu2x/utils/cls.py +157 -0
- Waifu2x/utils/image_quality.py +173 -0
- Waifu2x/utils/prepare_images.py +120 -0
- api.py +33 -0
- app.py +65 -0
.gitignore
ADDED
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# dev files
|
2 |
+
*.cache
|
3 |
+
*.dev.py
|
4 |
+
*.mv
|
5 |
+
state_dict/
|
6 |
+
integrated_datasets/
|
7 |
+
*.results
|
8 |
+
*.tokenizer
|
9 |
+
*.model
|
10 |
+
*.state_dict
|
11 |
+
*.config
|
12 |
+
*.args
|
13 |
+
*.zip
|
14 |
+
*.gz
|
15 |
+
*.bin
|
16 |
+
*.result.txt
|
17 |
+
*.DS_Store
|
18 |
+
*.tmp
|
19 |
+
*.args.txt
|
20 |
+
*.summary.txt
|
21 |
+
*.dat
|
22 |
+
*.graph
|
23 |
+
# Byte-compiled / optimized / DLL files
|
24 |
+
__pycache__/
|
25 |
+
*.py[cod]
|
26 |
+
*$py.class
|
27 |
+
*.pyc
|
28 |
+
experiments/
|
29 |
+
tests/
|
30 |
+
*.result.json
|
31 |
+
.idea/
|
32 |
+
imgs/
|
33 |
+
|
34 |
+
# Embedding
|
35 |
+
glove.840B.300d.txt
|
36 |
+
glove.42B.300d.txt
|
37 |
+
glove.twitter.27B.txt
|
38 |
+
|
39 |
+
# project main files
|
40 |
+
release_note.json
|
41 |
+
|
42 |
+
# C extensions
|
43 |
+
*.so
|
44 |
+
|
45 |
+
# Distribution / packaging
|
46 |
+
.Python
|
47 |
+
build/
|
48 |
+
develop-eggs/
|
49 |
+
dist/
|
50 |
+
downloads/
|
51 |
+
eggs/
|
52 |
+
.eggs/
|
53 |
+
lib64/
|
54 |
+
parts/
|
55 |
+
sdist/
|
56 |
+
var/
|
57 |
+
wheels/
|
58 |
+
pip-wheel-metadata/
|
59 |
+
share/python-wheels/
|
60 |
+
*.egg-info/
|
61 |
+
.installed.cfg
|
62 |
+
*.egg
|
63 |
+
MANIFEST
|
64 |
+
|
65 |
+
# PyInstaller
|
66 |
+
# Usually these files are written by a python script from a template
|
67 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
68 |
+
*.manifest
|
69 |
+
*.spec
|
70 |
+
|
71 |
+
# Installer training_logs
|
72 |
+
pip-log.txt
|
73 |
+
pip-delete-this-directory.txt
|
74 |
+
|
75 |
+
# Unit test / coverage reports
|
76 |
+
htmlcov/
|
77 |
+
.tox/
|
78 |
+
.nox/
|
79 |
+
.coverage
|
80 |
+
.coverage.*
|
81 |
+
.cache
|
82 |
+
nosetests.xml
|
83 |
+
coverage.xml
|
84 |
+
*.cover
|
85 |
+
*.py,cover
|
86 |
+
.hypothesis/
|
87 |
+
.pytest_cache/
|
88 |
+
|
89 |
+
# Translations
|
90 |
+
*.mo
|
91 |
+
*.pot
|
92 |
+
|
93 |
+
# Django stuff:
|
94 |
+
*.log
|
95 |
+
local_settings.py
|
96 |
+
db.sqlite3
|
97 |
+
db.sqlite3-journal
|
98 |
+
|
99 |
+
# Flask stuff:
|
100 |
+
instance/
|
101 |
+
.webassets-cache
|
102 |
+
|
103 |
+
# Scrapy stuff:
|
104 |
+
.scrapy
|
105 |
+
|
106 |
+
# Sphinx documentation
|
107 |
+
docs/_build/
|
108 |
+
|
109 |
+
# PyBuilder
|
110 |
+
target/
|
111 |
+
|
112 |
+
# Jupyter Notebook
|
113 |
+
.ipynb_checkpoints
|
114 |
+
|
115 |
+
# IPython
|
116 |
+
profile_default/
|
117 |
+
ipython_config.py
|
118 |
+
|
119 |
+
# pyenv
|
120 |
+
.python-version
|
121 |
+
|
122 |
+
# pipenv
|
123 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
124 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
125 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
126 |
+
# install all needed dependencies.
|
127 |
+
#Pipfile.lock
|
128 |
+
|
129 |
+
# celery beat schedule file
|
130 |
+
celerybeat-schedule
|
131 |
+
|
132 |
+
# SageMath parsed files
|
133 |
+
*.sage.py
|
134 |
+
|
135 |
+
# Environments
|
136 |
+
.env
|
137 |
+
.venv
|
138 |
+
env/
|
139 |
+
venv/
|
140 |
+
ENV/
|
141 |
+
env.bak/
|
142 |
+
venv.bak/
|
143 |
+
|
144 |
+
# Spyder project settings
|
145 |
+
.spyderproject
|
146 |
+
.spyproject
|
147 |
+
|
148 |
+
# Rope project settings
|
149 |
+
.ropeproject
|
150 |
+
|
151 |
+
# mkdocs documentation
|
152 |
+
/site
|
153 |
+
|
154 |
+
# mypy
|
155 |
+
.mypy_cache/
|
156 |
+
.dmypy.json
|
157 |
+
dmypy.json
|
158 |
+
|
159 |
+
# Pyre type checker
|
160 |
+
.pyre/
|
161 |
+
.DS_Store
|
162 |
+
examples/.DS_Store
|
.idea/.gitignore
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Default ignored files
|
2 |
+
/shelf/
|
3 |
+
/workspace.xml
|
4 |
+
# Editor-based HTTP Client requests
|
5 |
+
/httpRequests/
|
6 |
+
# Datasource local storage ignored files
|
7 |
+
/dataSources/
|
8 |
+
/dataSources.local.xml
|
.idea/Waifu2X-Image-Scale.iml
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<module type="PYTHON_MODULE" version="4">
|
3 |
+
<component name="NewModuleRootManager">
|
4 |
+
<content url="file://$MODULE_DIR$" />
|
5 |
+
<orderEntry type="inheritedJdk" />
|
6 |
+
<orderEntry type="sourceFolder" forTests="false" />
|
7 |
+
</component>
|
8 |
+
</module>
|
.idea/deployment.xml
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<project version="4">
|
3 |
+
<component name="PublishConfigData" remoteFilesAllowedToDisappearOnAutoupload="false">
|
4 |
+
<serverData>
|
5 |
+
<paths name="RTX3090 #1">
|
6 |
+
<serverdata>
|
7 |
+
<mappings>
|
8 |
+
<mapping local="$PROJECT_DIR$" web="/" />
|
9 |
+
</mappings>
|
10 |
+
</serverdata>
|
11 |
+
</paths>
|
12 |
+
</serverData>
|
13 |
+
</component>
|
14 |
+
</project>
|
.idea/inspectionProfiles/Project_Default.xml
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<component name="InspectionProjectProfileManager">
|
2 |
+
<profile version="1.0">
|
3 |
+
<option name="myName" value="Project Default" />
|
4 |
+
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
|
5 |
+
<option name="ignoredPackages">
|
6 |
+
<value>
|
7 |
+
<list size="3">
|
8 |
+
<item index="0" class="java.lang.String" itemvalue="ftfy" />
|
9 |
+
<item index="1" class="java.lang.String" itemvalue="gensim" />
|
10 |
+
<item index="2" class="java.lang.String" itemvalue="diffusers" />
|
11 |
+
</list>
|
12 |
+
</value>
|
13 |
+
</option>
|
14 |
+
</inspection_tool>
|
15 |
+
</profile>
|
16 |
+
</component>
|
.idea/inspectionProfiles/profiles_settings.xml
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<component name="InspectionProjectProfileManager">
|
2 |
+
<settings>
|
3 |
+
<option name="USE_PROJECT_PROFILE" value="false" />
|
4 |
+
<version value="1.0" />
|
5 |
+
</settings>
|
6 |
+
</component>
|
.idea/misc.xml
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<project version="4">
|
3 |
+
<component name="ProjectRootManager" version="2" project-jdk-name="base" project-jdk-type="Python SDK" />
|
4 |
+
</project>
|
.idea/modules.xml
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<project version="4">
|
3 |
+
<component name="ProjectModuleManager">
|
4 |
+
<modules>
|
5 |
+
<module fileurl="file://$PROJECT_DIR$/.idea/Waifu2X-Image-Scale.iml" filepath="$PROJECT_DIR$/.idea/Waifu2X-Image-Scale.iml" />
|
6 |
+
</modules>
|
7 |
+
</component>
|
8 |
+
</project>
|
.idea/vcs.xml
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<project version="4">
|
3 |
+
<component name="VcsDirectoryMappings">
|
4 |
+
<mapping directory="" vcs="Git" />
|
5 |
+
</component>
|
6 |
+
</project>
|
Waifu2x/.gitattributes
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
Readme_imgs/* linguist-documentation
|
Waifu2x/.gitignore
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
*.xml
|
3 |
+
*.iml
|
4 |
+
*.pyc
|
Waifu2x/Common.py
ADDED
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from contextlib import contextmanager
|
2 |
+
from math import sqrt, log
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
|
7 |
+
|
8 |
+
# import warnings
|
9 |
+
# warnings.simplefilter('ignore')
|
10 |
+
|
11 |
+
|
12 |
+
class BaseModule(nn.Module):
|
13 |
+
def __init__(self):
|
14 |
+
self.act_fn = None
|
15 |
+
super(BaseModule, self).__init__()
|
16 |
+
|
17 |
+
def selu_init_params(self):
|
18 |
+
for m in self.modules():
|
19 |
+
if isinstance(m, nn.Conv2d) and m.weight.requires_grad:
|
20 |
+
m.weight.data.normal_(0.0, 1.0 / sqrt(m.weight.numel()))
|
21 |
+
if m.bias is not None:
|
22 |
+
m.bias.data.fill_(0)
|
23 |
+
elif isinstance(m, nn.BatchNorm2d) and m.weight.requires_grad:
|
24 |
+
m.weight.data.fill_(1)
|
25 |
+
m.bias.data.zero_()
|
26 |
+
|
27 |
+
elif isinstance(m, nn.Linear) and m.weight.requires_grad:
|
28 |
+
m.weight.data.normal_(0, 1.0 / sqrt(m.weight.numel()))
|
29 |
+
m.bias.data.zero_()
|
30 |
+
|
31 |
+
def initialize_weights_xavier_uniform(self):
|
32 |
+
for m in self.modules():
|
33 |
+
if isinstance(m, nn.Conv2d) and m.weight.requires_grad:
|
34 |
+
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='leaky_relu')
|
35 |
+
nn.init.xavier_uniform_(m.weight)
|
36 |
+
if m.bias is not None:
|
37 |
+
m.bias.data.zero_()
|
38 |
+
elif isinstance(m, nn.BatchNorm2d) and m.weight.requires_grad:
|
39 |
+
m.weight.data.fill_(1)
|
40 |
+
m.bias.data.zero_()
|
41 |
+
|
42 |
+
def load_state_dict(self, state_dict, strict=True, self_state=False):
|
43 |
+
own_state = self_state if self_state else self.state_dict()
|
44 |
+
for name, param in state_dict.items():
|
45 |
+
if name in own_state:
|
46 |
+
try:
|
47 |
+
own_state[name].copy_(param.data)
|
48 |
+
except Exception as e:
|
49 |
+
print("Parameter {} fails to load.".format(name))
|
50 |
+
print("-----------------------------------------")
|
51 |
+
print(e)
|
52 |
+
else:
|
53 |
+
print("Parameter {} is not in the model. ".format(name))
|
54 |
+
|
55 |
+
@contextmanager
|
56 |
+
def set_activation_inplace(self):
|
57 |
+
if hasattr(self, 'act_fn') and hasattr(self.act_fn, 'inplace'):
|
58 |
+
# save memory
|
59 |
+
self.act_fn.inplace = True
|
60 |
+
yield
|
61 |
+
self.act_fn.inplace = False
|
62 |
+
else:
|
63 |
+
yield
|
64 |
+
|
65 |
+
def total_parameters(self):
|
66 |
+
total = sum([i.numel() for i in self.parameters()])
|
67 |
+
trainable = sum([i.numel() for i in self.parameters() if i.requires_grad])
|
68 |
+
print("Total parameters : {}. Trainable parameters : {}".format(total, trainable))
|
69 |
+
return total
|
70 |
+
|
71 |
+
def forward(self, *x):
|
72 |
+
raise NotImplementedError
|
73 |
+
|
74 |
+
|
75 |
+
class ResidualFixBlock(BaseModule):
|
76 |
+
def __init__(self, in_channels, out_channels, kernel_size=3, padding=1, dilation=1,
|
77 |
+
groups=1, activation=nn.SELU(), conv=nn.Conv2d):
|
78 |
+
super(ResidualFixBlock, self).__init__()
|
79 |
+
self.act_fn = activation
|
80 |
+
self.m = nn.Sequential(
|
81 |
+
conv(in_channels, out_channels, kernel_size, padding=padding, dilation=dilation, groups=groups),
|
82 |
+
activation,
|
83 |
+
# conv(out_channels, out_channels, kernel_size, padding=(kernel_size - 1) // 2, dilation=1, groups=groups),
|
84 |
+
conv(in_channels, out_channels, kernel_size, padding=padding, dilation=dilation, groups=groups),
|
85 |
+
)
|
86 |
+
|
87 |
+
def forward(self, x):
|
88 |
+
out = self.m(x)
|
89 |
+
return self.act_fn(out + x)
|
90 |
+
|
91 |
+
|
92 |
+
class ConvBlock(BaseModule):
|
93 |
+
def __init__(self, in_channels, out_channels, kernel_size=3, padding=1, dilation=1, groups=1,
|
94 |
+
activation=nn.SELU(), conv=nn.Conv2d):
|
95 |
+
super(ConvBlock, self).__init__()
|
96 |
+
self.m = nn.Sequential(conv(in_channels, out_channels, kernel_size, padding=padding,
|
97 |
+
dilation=dilation, groups=groups),
|
98 |
+
activation)
|
99 |
+
|
100 |
+
def forward(self, x):
|
101 |
+
return self.m(x)
|
102 |
+
|
103 |
+
|
104 |
+
class UpSampleBlock(BaseModule):
|
105 |
+
def __init__(self, channels, scale, activation, atrous_rate=1, conv=nn.Conv2d):
|
106 |
+
assert scale in [2, 4, 8], "Currently UpSampleBlock supports 2, 4, 8 scaling"
|
107 |
+
super(UpSampleBlock, self).__init__()
|
108 |
+
m = nn.Sequential(
|
109 |
+
conv(channels, 4 * channels, kernel_size=3, padding=atrous_rate, dilation=atrous_rate),
|
110 |
+
activation,
|
111 |
+
nn.PixelShuffle(2)
|
112 |
+
)
|
113 |
+
self.m = nn.Sequential(*[m for _ in range(int(log(scale, 2)))])
|
114 |
+
|
115 |
+
def forward(self, x):
|
116 |
+
return self.m(x)
|
117 |
+
|
118 |
+
|
119 |
+
class SpatialChannelSqueezeExcitation(BaseModule):
|
120 |
+
# https://arxiv.org/abs/1709.01507
|
121 |
+
# https://arxiv.org/pdf/1803.02579v1.pdf
|
122 |
+
def __init__(self, in_channel, reduction=16, activation=nn.ReLU()):
|
123 |
+
super(SpatialChannelSqueezeExcitation, self).__init__()
|
124 |
+
linear_nodes = max(in_channel // reduction, 4) # avoid only 1 node case
|
125 |
+
self.avg_pool = nn.AdaptiveAvgPool2d(1)
|
126 |
+
self.channel_excite = nn.Sequential(
|
127 |
+
# check the paper for the number 16 in reduction. It is selected by experiment.
|
128 |
+
nn.Linear(in_channel, linear_nodes),
|
129 |
+
activation,
|
130 |
+
nn.Linear(linear_nodes, in_channel),
|
131 |
+
nn.Sigmoid()
|
132 |
+
)
|
133 |
+
self.spatial_excite = nn.Sequential(
|
134 |
+
nn.Conv2d(in_channel, 1, kernel_size=1, stride=1, padding=0, bias=False),
|
135 |
+
nn.Sigmoid()
|
136 |
+
)
|
137 |
+
|
138 |
+
def forward(self, x):
|
139 |
+
b, c, h, w = x.size()
|
140 |
+
#
|
141 |
+
channel = self.avg_pool(x).view(b, c)
|
142 |
+
# channel = F.avg_pool2d(x, kernel_size=(h,w)).view(b,c) # used for porting to other frameworks
|
143 |
+
cSE = self.channel_excite(channel).view(b, c, 1, 1)
|
144 |
+
x_cSE = torch.mul(x, cSE)
|
145 |
+
|
146 |
+
# spatial
|
147 |
+
sSE = self.spatial_excite(x)
|
148 |
+
x_sSE = torch.mul(x, sSE)
|
149 |
+
# return x_sSE
|
150 |
+
return torch.add(x_cSE, x_sSE)
|
151 |
+
|
152 |
+
|
153 |
+
class PartialConv(nn.Module):
|
154 |
+
# reference:
|
155 |
+
# Image Inpainting for Irregular Holes Using Partial Convolutions
|
156 |
+
# http://masc.cs.gmu.edu/wiki/partialconv/show?time=2018-05-24+21%3A41%3A10
|
157 |
+
# https://github.com/naoto0804/pytorch-inpainting-with-partial-conv/blob/master/net.py
|
158 |
+
# https://github.com/SeitaroShinagawa/chainer-partial_convolution_image_inpainting/blob/master/common/net.py
|
159 |
+
# partial based padding
|
160 |
+
# https: // github.com / NVIDIA / partialconv / blob / master / models / pd_resnet.py
|
161 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
162 |
+
padding=0, dilation=1, groups=1, bias=True):
|
163 |
+
|
164 |
+
super(PartialConv, self).__init__()
|
165 |
+
self.feature_conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride,
|
166 |
+
padding, dilation, groups, bias)
|
167 |
+
|
168 |
+
self.mask_conv = nn.Conv2d(1, 1, kernel_size, stride,
|
169 |
+
padding, dilation, groups, bias=False)
|
170 |
+
self.window_size = self.mask_conv.kernel_size[0] * self.mask_conv.kernel_size[1]
|
171 |
+
torch.nn.init.constant_(self.mask_conv.weight, 1.0)
|
172 |
+
|
173 |
+
for param in self.mask_conv.parameters():
|
174 |
+
param.requires_grad = False
|
175 |
+
|
176 |
+
def forward(self, x):
|
177 |
+
output = self.feature_conv(x)
|
178 |
+
if self.feature_conv.bias is not None:
|
179 |
+
output_bias = self.feature_conv.bias.view(1, -1, 1, 1).expand_as(output)
|
180 |
+
else:
|
181 |
+
output_bias = torch.zeros_like(output, device=x.device)
|
182 |
+
|
183 |
+
with torch.no_grad():
|
184 |
+
ones = torch.ones(1, 1, x.size(2), x.size(3), device=x.device)
|
185 |
+
output_mask = self.mask_conv(ones)
|
186 |
+
output_mask = self.window_size / output_mask
|
187 |
+
output = (output - output_bias) * output_mask + output_bias
|
188 |
+
|
189 |
+
return output
|
Waifu2x/Dataloader.py
ADDED
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import glob
|
2 |
+
import io
|
3 |
+
import numpy as np
|
4 |
+
import re
|
5 |
+
import os
|
6 |
+
import random
|
7 |
+
from io import BytesIO
|
8 |
+
from uuid import uuid4
|
9 |
+
import sqlite3
|
10 |
+
import h5py
|
11 |
+
import torch
|
12 |
+
from PIL import Image
|
13 |
+
from torch.utils.data import Dataset
|
14 |
+
from torchvision.transforms import RandomCrop
|
15 |
+
from torchvision.transforms.functional import to_tensor
|
16 |
+
|
17 |
+
|
18 |
+
class ImageH5Data(Dataset):
|
19 |
+
def __init__(self, h5py_file, folder_name):
|
20 |
+
self.data = h5py.File(h5py_file, 'r')[folder_name]
|
21 |
+
self.data_hr = self.data['train_hr']
|
22 |
+
self.data_lr = self.data['train_lr']
|
23 |
+
self.len_imgs = len(self.data_hr)
|
24 |
+
self.h5py_file = h5py_file
|
25 |
+
self.folder_name = folder_name
|
26 |
+
|
27 |
+
def __len__(self):
|
28 |
+
# with h5py.File(self.h5py_file, 'r') as f:
|
29 |
+
# return len(f[self.folder_name]['train_lr'])
|
30 |
+
return self.len_imgs
|
31 |
+
|
32 |
+
def __getitem__(self, index):
|
33 |
+
# with h5py.File(self.h5py_file, 'r') as f:
|
34 |
+
# data_lr = f[self.folder_name]['train_lr'][index]
|
35 |
+
# data_hr = f[self.folder_name]['train_lr'][index]
|
36 |
+
#
|
37 |
+
# return data_lr, data_hr
|
38 |
+
return self.data_lr[index], self.data_hr[index]
|
39 |
+
|
40 |
+
|
41 |
+
class ImageData(Dataset):
|
42 |
+
def __init__(self,
|
43 |
+
img_folder,
|
44 |
+
patch_size=96,
|
45 |
+
shrink_size=2,
|
46 |
+
noise_level=1,
|
47 |
+
down_sample_method=None,
|
48 |
+
color_mod='RGB',
|
49 |
+
dummy_len=None):
|
50 |
+
|
51 |
+
self.img_folder = img_folder
|
52 |
+
all_img = glob.glob(self.img_folder + "/**", recursive=True)
|
53 |
+
self.img = list(filter(lambda x: x.endswith('png') or x.endswith("jpg") or x.endswith("jpeg"), all_img))
|
54 |
+
self.total_img = len(self.img)
|
55 |
+
self.dummy_len = dummy_len if dummy_len is not None else self.total_img
|
56 |
+
self.random_cropper = RandomCrop(size=patch_size)
|
57 |
+
self.color_mod = color_mod
|
58 |
+
self.img_augmenter = ImageAugment(shrink_size, noise_level, down_sample_method)
|
59 |
+
|
60 |
+
def get_img_patches(self, img_file):
|
61 |
+
img_pil = Image.open(img_file).convert("RGB")
|
62 |
+
img_patch = self.random_cropper(img_pil)
|
63 |
+
lr_hr_patches = self.img_augmenter.process(img_patch)
|
64 |
+
return lr_hr_patches
|
65 |
+
|
66 |
+
def __len__(self):
|
67 |
+
return self.dummy_len # len(self.img)
|
68 |
+
|
69 |
+
def __getitem__(self, index):
|
70 |
+
idx = random.choice(range(0, self.total_img))
|
71 |
+
img = self.img[idx]
|
72 |
+
patch = self.get_img_patches(img)
|
73 |
+
if self.color_mod == 'RGB':
|
74 |
+
lr_img = patch[0].convert("RGB")
|
75 |
+
hr_img = patch[1].convert("RGB")
|
76 |
+
elif self.color_mod == 'YCbCr':
|
77 |
+
lr_img, _, _ = patch[0].convert('YCbCr').split()
|
78 |
+
hr_img, _, _ = patch[1].convert('YCbCr').split()
|
79 |
+
else:
|
80 |
+
raise KeyError('Either RGB or YCbCr')
|
81 |
+
return to_tensor(lr_img), to_tensor(hr_img)
|
82 |
+
|
83 |
+
|
84 |
+
class Image2Sqlite(ImageData):
|
85 |
+
def __getitem__(self, item):
|
86 |
+
img = self.img[item]
|
87 |
+
lr_hr_patch = self.get_img_patches(img)
|
88 |
+
if self.color_mod == 'RGB':
|
89 |
+
lr_img = lr_hr_patch[0].convert("RGB")
|
90 |
+
hr_img = lr_hr_patch[1].convert("RGB")
|
91 |
+
elif self.color_mod == 'YCbCr':
|
92 |
+
lr_img, _, _ = lr_hr_patch[0].convert('YCbCr').split()
|
93 |
+
hr_img, _, _ = lr_hr_patch[1].convert('YCbCr').split()
|
94 |
+
else:
|
95 |
+
raise KeyError('Either RGB or YCbCr')
|
96 |
+
lr_byte = self.convert_to_bytevalue(lr_img)
|
97 |
+
hr_byte = self.convert_to_bytevalue(hr_img)
|
98 |
+
return [lr_byte, hr_byte]
|
99 |
+
|
100 |
+
@staticmethod
|
101 |
+
def convert_to_bytevalue(pil_img):
|
102 |
+
img_byte = io.BytesIO()
|
103 |
+
pil_img.save(img_byte, format='png')
|
104 |
+
return img_byte.getvalue()
|
105 |
+
|
106 |
+
|
107 |
+
class ImageDBData(Dataset):
|
108 |
+
def __init__(self, db_file, db_table="images", lr_col="lr_img", hr_col="hr_img", max_images=None):
|
109 |
+
self.db_file = db_file
|
110 |
+
self.db_table = db_table
|
111 |
+
self.lr_col = lr_col
|
112 |
+
self.hr_col = hr_col
|
113 |
+
self.total_images = self.get_num_rows(max_images)
|
114 |
+
# self.lr_hr_images = self.get_all_images()
|
115 |
+
|
116 |
+
def __len__(self):
|
117 |
+
return self.total_images
|
118 |
+
|
119 |
+
# def get_all_images(self):
|
120 |
+
# with sqlite3.connect(self.db_file) as conn:
|
121 |
+
# cursor = conn.cursor()
|
122 |
+
# cursor.execute(f"SELECT * FROM {self.db_table} LIMIT {self.total_images}")
|
123 |
+
# return cursor.fetchall()
|
124 |
+
|
125 |
+
def get_num_rows(self, max_images):
|
126 |
+
with sqlite3.connect(self.db_file) as conn:
|
127 |
+
cursor = conn.cursor()
|
128 |
+
cursor.execute(f"SELECT MAX(ROWID) FROM {self.db_table}")
|
129 |
+
db_rows = cursor.fetchone()[0]
|
130 |
+
if max_images:
|
131 |
+
return min(max_images, db_rows)
|
132 |
+
else:
|
133 |
+
return db_rows
|
134 |
+
|
135 |
+
def __getitem__(self, item):
|
136 |
+
# lr, hr = self.lr_hr_images[item]
|
137 |
+
# lr = Image.open(io.BytesIO(lr))
|
138 |
+
# hr = Image.open(io.BytesIO(hr))
|
139 |
+
# return to_tensor(lr), to_tensor(hr)
|
140 |
+
# note sqlite rowid starts with 1
|
141 |
+
with sqlite3.connect(self.db_file) as conn:
|
142 |
+
cursor = conn.cursor()
|
143 |
+
cursor.execute(f"SELECT {self.lr_col}, {self.hr_col} FROM {self.db_table} WHERE ROWID={item + 1}")
|
144 |
+
lr, hr = cursor.fetchone()
|
145 |
+
lr = Image.open(io.BytesIO(lr)).convert("RGB")
|
146 |
+
hr = Image.open(io.BytesIO(hr)).convert("RGB")
|
147 |
+
# lr = np.array(lr) # use scale [0, 255] instead of [0,1]
|
148 |
+
# hr = np.array(hr)
|
149 |
+
return to_tensor(lr), to_tensor(hr)
|
150 |
+
|
151 |
+
|
152 |
+
class ImagePatchData(Dataset):
|
153 |
+
def __init__(self, lr_folder, hr_folder):
|
154 |
+
self.lr_folder = lr_folder
|
155 |
+
self.hr_folder = hr_folder
|
156 |
+
self.lr_imgs = glob.glob(os.path.join(lr_folder, "**"))
|
157 |
+
self.total_imgs = len(self.lr_imgs)
|
158 |
+
|
159 |
+
def __len__(self):
|
160 |
+
return self.total_imgs
|
161 |
+
|
162 |
+
def __getitem__(self, item):
|
163 |
+
lr_file = self.lr_imgs[item]
|
164 |
+
hr_path = re.sub("lr", 'hr', os.path.dirname(lr_file))
|
165 |
+
filename = os.path.basename(lr_file)
|
166 |
+
hr_file = os.path.join(hr_path, filename)
|
167 |
+
return to_tensor(Image.open(lr_file)), to_tensor(Image.open(hr_file))
|
168 |
+
|
169 |
+
|
170 |
+
class ImageAugment:
|
171 |
+
def __init__(self,
|
172 |
+
shrink_size=2,
|
173 |
+
noise_level=1,
|
174 |
+
down_sample_method=None
|
175 |
+
):
|
176 |
+
# noise_level (int): 0: no noise; 1: 75-95% quality; 2:50-75%
|
177 |
+
if noise_level == 0:
|
178 |
+
self.noise_level = [0, 0]
|
179 |
+
elif noise_level == 1:
|
180 |
+
self.noise_level = [5, 25]
|
181 |
+
elif noise_level == 2:
|
182 |
+
self.noise_level = [25, 50]
|
183 |
+
else:
|
184 |
+
raise KeyError("Noise level should be either 0, 1, 2")
|
185 |
+
self.shrink_size = shrink_size
|
186 |
+
self.down_sample_method = down_sample_method
|
187 |
+
|
188 |
+
def shrink_img(self, hr_img):
|
189 |
+
|
190 |
+
if self.down_sample_method is None:
|
191 |
+
resample_method = random.choice([Image.BILINEAR, Image.BICUBIC, Image.LANCZOS])
|
192 |
+
else:
|
193 |
+
resample_method = self.down_sample_method
|
194 |
+
img_w, img_h = tuple(map(lambda x: int(x / self.shrink_size), hr_img.size))
|
195 |
+
lr_img = hr_img.resize((img_w, img_h), resample_method)
|
196 |
+
return lr_img
|
197 |
+
|
198 |
+
def add_jpeg_noise(self, hr_img):
|
199 |
+
quality = 100 - round(random.uniform(*self.noise_level))
|
200 |
+
lr_img = BytesIO()
|
201 |
+
hr_img.save(lr_img, format='JPEG', quality=quality)
|
202 |
+
lr_img.seek(0)
|
203 |
+
lr_img = Image.open(lr_img)
|
204 |
+
return lr_img
|
205 |
+
|
206 |
+
def process(self, hr_patch_pil):
|
207 |
+
lr_patch_pil = self.shrink_img(hr_patch_pil)
|
208 |
+
if self.noise_level[1] > 0:
|
209 |
+
lr_patch_pil = self.add_jpeg_noise(lr_patch_pil)
|
210 |
+
|
211 |
+
return lr_patch_pil, hr_patch_pil
|
212 |
+
|
213 |
+
def up_sample(self, img, resample):
|
214 |
+
width, height = img.size
|
215 |
+
return img.resize((self.shrink_size * width, self.shrink_size * height), resample=resample)
|
Waifu2x/Img_to_Sqlite.py
ADDED
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Split images into small patches and insert them into sqlite db. Reading and Inserting speeds are much better than
|
3 |
+
Ubuntu's (18.04) file system when the number of patches is larger than 20k. And it has smaller size than using h5 format
|
4 |
+
|
5 |
+
Recommend to check or filter out small size patches as their content vary little. 128x128 seems better than 64x64.
|
6 |
+
|
7 |
+
|
8 |
+
"""
|
9 |
+
import sqlite3
|
10 |
+
from torch.utils.data import DataLoader
|
11 |
+
from tqdm import trange
|
12 |
+
from Dataloader import Image2Sqlite
|
13 |
+
|
14 |
+
conn = sqlite3.connect('dataset/image_yandere.db')
|
15 |
+
cursor = conn.cursor()
|
16 |
+
|
17 |
+
with conn:
|
18 |
+
cursor.execute("PRAGMA SYNCHRONOUS = OFF")
|
19 |
+
|
20 |
+
table_name = "train_images_size_128_noise_1_rgb"
|
21 |
+
lr_col = "lr_img"
|
22 |
+
hr_col = "hr_img"
|
23 |
+
|
24 |
+
with conn:
|
25 |
+
conn.execute(f"CREATE TABLE IF NOT EXISTS {table_name} ({lr_col} BLOB, {hr_col} BLOB)")
|
26 |
+
|
27 |
+
dat = Image2Sqlite(img_folder='./dataset/yande.re_test_shrink',
|
28 |
+
patch_size=256,
|
29 |
+
shrink_size=2,
|
30 |
+
noise_level=1,
|
31 |
+
down_sample_method=None,
|
32 |
+
color_mod='RGB',
|
33 |
+
dummy_len=None)
|
34 |
+
print(f"Total images {len(dat)}")
|
35 |
+
|
36 |
+
img_dat = DataLoader(dat, num_workers=6, batch_size=6, shuffle=True)
|
37 |
+
|
38 |
+
num_batches = 20
|
39 |
+
for i in trange(num_batches):
|
40 |
+
bulk = []
|
41 |
+
for lrs, hrs in img_dat:
|
42 |
+
patches = [(lrs[i], hrs[i]) for i in range(len(lrs))]
|
43 |
+
# patches = [(lrs[i], hrs[i]) for i in range(len(lrs)) if len(lrs[i]) > 14000]
|
44 |
+
|
45 |
+
bulk.extend(patches)
|
46 |
+
|
47 |
+
bulk = [i for i in bulk if len(i[0]) > 15000] # for 128x128, 14000 is fair. Around 20% of patches are filtered out
|
48 |
+
cursor.executemany(f"INSERT INTO {table_name}({lr_col}, {hr_col}) VALUES (?,?)", bulk)
|
49 |
+
conn.commit()
|
50 |
+
|
51 |
+
cursor.execute(f"select max(rowid) from {table_name}")
|
52 |
+
print(cursor.fetchall())
|
53 |
+
conn.commit()
|
54 |
+
# +++++++++++++++++++++++++++++++++++++
|
55 |
+
# Used for Create Test Database
|
56 |
+
# -------------------------------------
|
57 |
+
|
58 |
+
# cursor.execute(f"SELECT ROWID FROM {table_name} ORDER BY LENGTH({lr_col}) DESC LIMIT 400")
|
59 |
+
# rowdis = cursor.fetchall()
|
60 |
+
# rowdis = ",".join([str(i[0]) for i in rowdis])
|
61 |
+
#
|
62 |
+
# cursor.execute(f"DELETE FROM {table_name} WHERE ROWID NOT IN ({rowdis})")
|
63 |
+
# conn.commit()
|
64 |
+
# cursor.execute("vacuum")
|
65 |
+
#
|
66 |
+
# cursor.execute("""
|
67 |
+
# CREATE TABLE IF NOT EXISTS train_images_size_128_noise_1_rgb_small AS
|
68 |
+
# SELECT *
|
69 |
+
# FROM train_images_size_128_noise_1_rgb
|
70 |
+
# WHERE length(lr_img) < 14000;
|
71 |
+
# """)
|
72 |
+
#
|
73 |
+
# cursor.execute("""
|
74 |
+
# DELETE
|
75 |
+
# FROM train_images_size_128_noise_1_rgb
|
76 |
+
# WHERE length(lr_img) < 14000;
|
77 |
+
# """)
|
78 |
+
|
79 |
+
# reset index
|
80 |
+
cursor.execute("VACUUM")
|
81 |
+
conn.commit()
|
82 |
+
|
83 |
+
# +++++++++++++++++++++++++++++++++++++
|
84 |
+
# check image size
|
85 |
+
# -------------------------------------
|
86 |
+
#
|
87 |
+
|
88 |
+
from PIL import Image
|
89 |
+
import io
|
90 |
+
|
91 |
+
cursor.execute(
|
92 |
+
f"""
|
93 |
+
select {hr_col} from {table_name}
|
94 |
+
ORDER BY LENGTH({hr_col}) desc
|
95 |
+
limit 100
|
96 |
+
"""
|
97 |
+
)
|
98 |
+
# WHERE LENGTH({lr_col}) BETWEEN 14000 AND 16000
|
99 |
+
|
100 |
+
# small = cursor.fetchall()
|
101 |
+
# print(len(small))
|
102 |
+
for idx, i in enumerate(cursor):
|
103 |
+
img = Image.open(io.BytesIO(i[0]))
|
104 |
+
img.save(f"dataset/check/{idx}.png")
|
105 |
+
|
106 |
+
# +++++++++++++++++++++++++++++++++++++
|
107 |
+
# Check Image Variance
|
108 |
+
# -------------------------------------
|
109 |
+
|
110 |
+
import pandas as pd
|
111 |
+
import matplotlib.pyplot as plt
|
112 |
+
|
113 |
+
dat = pd.read_sql(f"SELECT length({lr_col}) from {table_name}", conn)
|
114 |
+
dat.hist(bins=20)
|
115 |
+
plt.show()
|
Waifu2x/LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<http://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
Waifu2x/Loss.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn
|
3 |
+
from torch.nn.functional import _pointwise_loss
|
4 |
+
|
5 |
+
rgb_weights = [0.29891 * 3, 0.58661 * 3, 0.11448 * 3]
|
6 |
+
# RGB have different weights
|
7 |
+
# https://github.com/nagadomi/waifu2x/blob/master/train.lua#L109
|
8 |
+
use_cuda = torch.cuda.is_available()
|
9 |
+
FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor
|
10 |
+
LongTensor = torch.cuda.LongTensor if use_cuda else torch.LongTensor
|
11 |
+
Tensor = FloatTensor
|
12 |
+
|
13 |
+
|
14 |
+
class WeightedHuberLoss(nn.SmoothL1Loss):
|
15 |
+
def __init__(self, weights=rgb_weights):
|
16 |
+
super(WeightedHuberLoss, self).__init__(size_average=True, reduce=True)
|
17 |
+
self.weights = torch.FloatTensor(weights).view(3, 1, 1)
|
18 |
+
|
19 |
+
def forward(self, input_data, target):
|
20 |
+
diff = torch.abs(input_data - target)
|
21 |
+
z = torch.where(diff < 1, 0.5 * torch.pow(diff, 2), (diff - 0.5))
|
22 |
+
out = z * self.weights.expand_as(diff)
|
23 |
+
return out.mean()
|
24 |
+
|
25 |
+
|
26 |
+
def weighted_mse_loss(input, target, weights):
|
27 |
+
out = (input - target) ** 2
|
28 |
+
out = out * weights.expand_as(out)
|
29 |
+
loss = out.sum(0) # or sum over whatever dimensions
|
30 |
+
return loss / out.size(0)
|
31 |
+
|
32 |
+
|
33 |
+
class WeightedL1Loss(nn.SmoothL1Loss):
|
34 |
+
def __init__(self, weights=rgb_weights):
|
35 |
+
super(WeightedHuberLoss, self).__init__(size_average=True, reduce=True)
|
36 |
+
self.weights = torch.FloatTensor(weights).view(3, 1, 1)
|
37 |
+
|
38 |
+
def forward(self, input_data, target):
|
39 |
+
return self.l1_loss(input_data, target, size_average=self.size_average,
|
40 |
+
reduce=self.reduce)
|
41 |
+
|
42 |
+
def l1_loss(self, input_data, target, size_average=True, reduce=True):
|
43 |
+
return _pointwise_loss(lambda a, b: torch.abs(a - b) * self.weights.expand_as(a),
|
44 |
+
torch._C._nn.l1_loss, input_data, target, size_average, reduce)
|
Waifu2x/Models.py
ADDED
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
from collections import OrderedDict
|
3 |
+
from math import exp
|
4 |
+
|
5 |
+
from .Common import *
|
6 |
+
|
7 |
+
|
8 |
+
# +++++++++++++++++++++++++++++++++++++
|
9 |
+
# FP16 Training
|
10 |
+
# -------------------------------------
|
11 |
+
# Modified from Nvidia/Apex
|
12 |
+
# https://github.com/NVIDIA/apex/blob/master/apex/fp16_utils/fp16util.py
|
13 |
+
|
14 |
+
class tofp16(nn.Module):
|
15 |
+
def __init__(self):
|
16 |
+
super(tofp16, self).__init__()
|
17 |
+
|
18 |
+
def forward(self, input):
|
19 |
+
if input.is_cuda:
|
20 |
+
return input.half()
|
21 |
+
else: # PyTorch 1.0 doesn't support fp16 in CPU
|
22 |
+
return input.float()
|
23 |
+
|
24 |
+
|
25 |
+
def BN_convert_float(module):
|
26 |
+
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):
|
27 |
+
module.float()
|
28 |
+
for child in module.children():
|
29 |
+
BN_convert_float(child)
|
30 |
+
return module
|
31 |
+
|
32 |
+
|
33 |
+
def network_to_half(network):
|
34 |
+
return nn.Sequential(tofp16(), BN_convert_float(network.half()))
|
35 |
+
|
36 |
+
|
37 |
+
# warnings.simplefilter('ignore')
|
38 |
+
|
39 |
+
# +++++++++++++++++++++++++++++++++++++
|
40 |
+
# DCSCN
|
41 |
+
# -------------------------------------
|
42 |
+
|
43 |
+
class DCSCN(BaseModule):
|
44 |
+
# https://github.com/jiny2001/dcscn-super-resolution
|
45 |
+
def __init__(self,
|
46 |
+
color_channel=3,
|
47 |
+
up_scale=2,
|
48 |
+
feature_layers=12,
|
49 |
+
first_feature_filters=196,
|
50 |
+
last_feature_filters=48,
|
51 |
+
reconstruction_filters=128,
|
52 |
+
up_sampler_filters=32
|
53 |
+
):
|
54 |
+
super(DCSCN, self).__init__()
|
55 |
+
self.total_feature_channels = 0
|
56 |
+
self.total_reconstruct_filters = 0
|
57 |
+
self.upscale = up_scale
|
58 |
+
|
59 |
+
self.act_fn = nn.SELU(inplace=False)
|
60 |
+
self.feature_block = self.make_feature_extraction_block(color_channel,
|
61 |
+
feature_layers,
|
62 |
+
first_feature_filters,
|
63 |
+
last_feature_filters)
|
64 |
+
|
65 |
+
self.reconstruction_block = self.make_reconstruction_block(reconstruction_filters)
|
66 |
+
self.up_sampler = self.make_upsampler(up_sampler_filters, color_channel)
|
67 |
+
self.selu_init_params()
|
68 |
+
|
69 |
+
def selu_init_params(self):
|
70 |
+
for i in self.modules():
|
71 |
+
if isinstance(i, nn.Conv2d):
|
72 |
+
i.weight.data.normal_(0.0, 1.0 / sqrt(i.weight.numel()))
|
73 |
+
if i.bias is not None:
|
74 |
+
i.bias.data.fill_(0)
|
75 |
+
|
76 |
+
def conv_block(self, in_channel, out_channel, kernel_size):
|
77 |
+
m = OrderedDict([
|
78 |
+
# ("Padding", nn.ReplicationPad2d((kernel_size - 1) // 2)),
|
79 |
+
('Conv2d', nn.Conv2d(in_channel, out_channel, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)),
|
80 |
+
('Activation', self.act_fn)
|
81 |
+
])
|
82 |
+
|
83 |
+
return nn.Sequential(m)
|
84 |
+
|
85 |
+
def make_feature_extraction_block(self, color_channel, num_layers, first_filters, last_filters):
|
86 |
+
# input layer
|
87 |
+
feature_block = [("Feature 1", self.conv_block(color_channel, first_filters, 3))]
|
88 |
+
# exponential decay
|
89 |
+
# rest layers
|
90 |
+
alpha_rate = log(first_filters / last_filters) / (num_layers - 1)
|
91 |
+
filter_nums = [round(first_filters * exp(-alpha_rate * i)) for i in range(num_layers)]
|
92 |
+
|
93 |
+
self.total_feature_channels = sum(filter_nums)
|
94 |
+
|
95 |
+
layer_filters = [[filter_nums[i], filter_nums[i + 1], 3] for i in range(num_layers - 1)]
|
96 |
+
|
97 |
+
feature_block.extend([("Feature {}".format(index + 2), self.conv_block(*x))
|
98 |
+
for index, x in enumerate(layer_filters)])
|
99 |
+
return nn.Sequential(OrderedDict(feature_block))
|
100 |
+
|
101 |
+
def make_reconstruction_block(self, num_filters):
|
102 |
+
B1 = self.conv_block(self.total_feature_channels, num_filters // 2, 1)
|
103 |
+
B2 = self.conv_block(num_filters // 2, num_filters, 3)
|
104 |
+
m = OrderedDict([
|
105 |
+
("A", self.conv_block(self.total_feature_channels, num_filters, 1)),
|
106 |
+
("B", nn.Sequential(*[B1, B2]))
|
107 |
+
])
|
108 |
+
self.total_reconstruct_filters = num_filters * 2
|
109 |
+
return nn.Sequential(m)
|
110 |
+
|
111 |
+
def make_upsampler(self, out_channel, color_channel):
|
112 |
+
out = out_channel * self.upscale ** 2
|
113 |
+
m = OrderedDict([
|
114 |
+
('Conv2d_block', self.conv_block(self.total_reconstruct_filters, out, kernel_size=3)),
|
115 |
+
('PixelShuffle', nn.PixelShuffle(self.upscale)),
|
116 |
+
("Conv2d", nn.Conv2d(out_channel, color_channel, kernel_size=3, padding=1, bias=False))
|
117 |
+
])
|
118 |
+
|
119 |
+
return nn.Sequential(m)
|
120 |
+
|
121 |
+
def forward(self, x):
|
122 |
+
# residual learning
|
123 |
+
lr, lr_up = x
|
124 |
+
feature = []
|
125 |
+
for layer in self.feature_block.children():
|
126 |
+
lr = layer(lr)
|
127 |
+
feature.append(lr)
|
128 |
+
feature = torch.cat(feature, dim=1)
|
129 |
+
|
130 |
+
reconstruction = [layer(feature) for layer in self.reconstruction_block.children()]
|
131 |
+
reconstruction = torch.cat(reconstruction, dim=1)
|
132 |
+
|
133 |
+
lr = self.up_sampler(reconstruction)
|
134 |
+
return lr + lr_up
|
135 |
+
|
136 |
+
|
137 |
+
# +++++++++++++++++++++++++++++++++++++
|
138 |
+
# CARN
|
139 |
+
# -------------------------------------
|
140 |
+
|
141 |
+
class CARN_Block(BaseModule):
|
142 |
+
def __init__(self, channels, kernel_size=3, padding=1, dilation=1,
|
143 |
+
groups=1, activation=nn.SELU(), repeat=3,
|
144 |
+
SEBlock=False, conv=nn.Conv2d,
|
145 |
+
single_conv_size=1, single_conv_group=1):
|
146 |
+
super(CARN_Block, self).__init__()
|
147 |
+
m = []
|
148 |
+
for i in range(repeat):
|
149 |
+
m.append(ResidualFixBlock(channels, channels, kernel_size=kernel_size, padding=padding, dilation=dilation,
|
150 |
+
groups=groups, activation=activation, conv=conv))
|
151 |
+
if SEBlock:
|
152 |
+
m.append(SpatialChannelSqueezeExcitation(channels, reduction=channels))
|
153 |
+
self.blocks = nn.Sequential(*m)
|
154 |
+
self.singles = nn.Sequential(
|
155 |
+
*[ConvBlock(channels * (i + 2), channels, kernel_size=single_conv_size,
|
156 |
+
padding=(single_conv_size - 1) // 2, groups=single_conv_group,
|
157 |
+
activation=activation, conv=conv)
|
158 |
+
for i in range(repeat)])
|
159 |
+
|
160 |
+
def forward(self, x):
|
161 |
+
c0 = x
|
162 |
+
for block, single in zip(self.blocks, self.singles):
|
163 |
+
b = block(x)
|
164 |
+
c0 = c = torch.cat([c0, b], dim=1)
|
165 |
+
x = single(c)
|
166 |
+
|
167 |
+
return x
|
168 |
+
|
169 |
+
|
170 |
+
class CARN(BaseModule):
|
171 |
+
# Fast, Accurate, and Lightweight Super-Resolution with Cascading Residual Network
|
172 |
+
# https://github.com/nmhkahn/CARN-pytorch
|
173 |
+
def __init__(self,
|
174 |
+
color_channels=3,
|
175 |
+
mid_channels=64,
|
176 |
+
scale=2,
|
177 |
+
activation=nn.SELU(),
|
178 |
+
num_blocks=3,
|
179 |
+
conv=nn.Conv2d):
|
180 |
+
super(CARN, self).__init__()
|
181 |
+
|
182 |
+
self.color_channels = color_channels
|
183 |
+
self.mid_channels = mid_channels
|
184 |
+
self.scale = scale
|
185 |
+
|
186 |
+
self.entry_block = ConvBlock(color_channels, mid_channels, kernel_size=3, padding=1, activation=activation,
|
187 |
+
conv=conv)
|
188 |
+
self.blocks = nn.Sequential(
|
189 |
+
*[CARN_Block(mid_channels, kernel_size=3, padding=1, activation=activation, conv=conv,
|
190 |
+
single_conv_size=1, single_conv_group=1)
|
191 |
+
for _ in range(num_blocks)])
|
192 |
+
self.singles = nn.Sequential(
|
193 |
+
*[ConvBlock(mid_channels * (i + 2), mid_channels, kernel_size=1, padding=0,
|
194 |
+
activation=activation, conv=conv)
|
195 |
+
for i in range(num_blocks)])
|
196 |
+
|
197 |
+
self.upsampler = UpSampleBlock(mid_channels, scale=scale, activation=activation, conv=conv)
|
198 |
+
self.exit_conv = conv(mid_channels, color_channels, kernel_size=3, padding=1)
|
199 |
+
|
200 |
+
def forward(self, x):
|
201 |
+
x = self.entry_block(x)
|
202 |
+
c0 = x
|
203 |
+
for block, single in zip(self.blocks, self.singles):
|
204 |
+
b = block(x)
|
205 |
+
c0 = c = torch.cat([c0, b], dim=1)
|
206 |
+
x = single(c)
|
207 |
+
x = self.upsampler(x)
|
208 |
+
out = self.exit_conv(x)
|
209 |
+
return out
|
210 |
+
|
211 |
+
|
212 |
+
class CARN_V2(CARN):
|
213 |
+
def __init__(self, color_channels=3, mid_channels=64,
|
214 |
+
scale=2, activation=nn.LeakyReLU(0.1),
|
215 |
+
SEBlock=True, conv=nn.Conv2d,
|
216 |
+
atrous=(1, 1, 1), repeat_blocks=3,
|
217 |
+
single_conv_size=3, single_conv_group=1):
|
218 |
+
super(CARN_V2, self).__init__(color_channels=color_channels, mid_channels=mid_channels, scale=scale,
|
219 |
+
activation=activation, conv=conv)
|
220 |
+
|
221 |
+
num_blocks = len(atrous)
|
222 |
+
m = []
|
223 |
+
for i in range(num_blocks):
|
224 |
+
m.append(CARN_Block(mid_channels, kernel_size=3, padding=1, dilation=1,
|
225 |
+
activation=activation, SEBlock=SEBlock, conv=conv, repeat=repeat_blocks,
|
226 |
+
single_conv_size=single_conv_size, single_conv_group=single_conv_group))
|
227 |
+
|
228 |
+
self.blocks = nn.Sequential(*m)
|
229 |
+
|
230 |
+
self.singles = nn.Sequential(
|
231 |
+
*[ConvBlock(mid_channels * (i + 2), mid_channels, kernel_size=single_conv_size,
|
232 |
+
padding=(single_conv_size - 1) // 2, groups=single_conv_group,
|
233 |
+
activation=activation, conv=conv)
|
234 |
+
for i in range(num_blocks)])
|
235 |
+
|
236 |
+
def forward(self, x):
|
237 |
+
x = self.entry_block(x)
|
238 |
+
c0 = x
|
239 |
+
res = x
|
240 |
+
for block, single in zip(self.blocks, self.singles):
|
241 |
+
b = block(x)
|
242 |
+
c0 = c = torch.cat([c0, b], dim=1)
|
243 |
+
x = single(c)
|
244 |
+
x = x + res
|
245 |
+
x = self.upsampler(x)
|
246 |
+
out = self.exit_conv(x)
|
247 |
+
return out
|
248 |
+
|
249 |
+
|
250 |
+
# +++++++++++++++++++++++++++++++++++++
|
251 |
+
# original Waifu2x model
|
252 |
+
# -------------------------------------
|
253 |
+
|
254 |
+
|
255 |
+
class UpConv_7(BaseModule):
|
256 |
+
# https://github.com/nagadomi/waifu2x/blob/3c46906cb78895dbd5a25c3705994a1b2e873199/lib/srcnn.lua#L311
|
257 |
+
def __init__(self):
|
258 |
+
super(UpConv_7, self).__init__()
|
259 |
+
self.act_fn = nn.LeakyReLU(0.1, inplace=False)
|
260 |
+
self.offset = 7 # because of 0 padding
|
261 |
+
from torch.nn import ZeroPad2d
|
262 |
+
self.pad = ZeroPad2d(self.offset)
|
263 |
+
m = [nn.Conv2d(3, 16, 3, 1, 0),
|
264 |
+
self.act_fn,
|
265 |
+
nn.Conv2d(16, 32, 3, 1, 0),
|
266 |
+
self.act_fn,
|
267 |
+
nn.Conv2d(32, 64, 3, 1, 0),
|
268 |
+
self.act_fn,
|
269 |
+
nn.Conv2d(64, 128, 3, 1, 0),
|
270 |
+
self.act_fn,
|
271 |
+
nn.Conv2d(128, 128, 3, 1, 0),
|
272 |
+
self.act_fn,
|
273 |
+
nn.Conv2d(128, 256, 3, 1, 0),
|
274 |
+
self.act_fn,
|
275 |
+
# in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=
|
276 |
+
nn.ConvTranspose2d(256, 3, kernel_size=4, stride=2, padding=3, bias=False)
|
277 |
+
]
|
278 |
+
self.Sequential = nn.Sequential(*m)
|
279 |
+
|
280 |
+
def load_pre_train_weights(self, json_file):
|
281 |
+
with open(json_file) as f:
|
282 |
+
weights = json.load(f)
|
283 |
+
box = []
|
284 |
+
for i in weights:
|
285 |
+
box.append(i['weight'])
|
286 |
+
box.append(i['bias'])
|
287 |
+
own_state = self.state_dict()
|
288 |
+
for index, (name, param) in enumerate(own_state.items()):
|
289 |
+
own_state[name].copy_(torch.FloatTensor(box[index]))
|
290 |
+
|
291 |
+
def forward(self, x):
|
292 |
+
x = self.pad(x)
|
293 |
+
return self.Sequential.forward(x)
|
294 |
+
|
295 |
+
|
296 |
+
|
297 |
+
class Vgg_7(UpConv_7):
|
298 |
+
def __init__(self):
|
299 |
+
super(Vgg_7, self).__init__()
|
300 |
+
self.act_fn = nn.LeakyReLU(0.1, inplace=False)
|
301 |
+
self.offset = 7
|
302 |
+
m = [nn.Conv2d(3, 32, 3, 1, 0),
|
303 |
+
self.act_fn,
|
304 |
+
nn.Conv2d(32, 32, 3, 1, 0),
|
305 |
+
self.act_fn,
|
306 |
+
nn.Conv2d(32, 64, 3, 1, 0),
|
307 |
+
self.act_fn,
|
308 |
+
nn.Conv2d(64, 64, 3, 1, 0),
|
309 |
+
self.act_fn,
|
310 |
+
nn.Conv2d(64, 128, 3, 1, 0),
|
311 |
+
self.act_fn,
|
312 |
+
nn.Conv2d(128, 128, 3, 1, 0),
|
313 |
+
self.act_fn,
|
314 |
+
nn.Conv2d(128, 3, 3, 1, 0)
|
315 |
+
]
|
316 |
+
self.Sequential = nn.Sequential(*m)
|
Waifu2x/Readme.md
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Waifu2x
|
2 |
+
|
3 |
+
Re-implementation on the original [waifu2x](https://github.com/nagadomi/waifu2x) in PyTorch with additional super resolution models. This repo is mainly used to explore interesting super resolution models. User-friendly tools may not be available now ><.
|
4 |
+
|
5 |
+
## Dependencies
|
6 |
+
* Python 3x
|
7 |
+
* [PyTorch](https://pytorch.org/) >= 1 ( > 0.41 shall also work, but not guarantee)
|
8 |
+
* [Nvidia/Apex](https://github.com/NVIDIA/apex/) (used for mixed precision training, you may use the [python codes](https://github.com/NVIDIA/apex/tree/master/apex/fp16_utils) directly)
|
9 |
+
|
10 |
+
Optinal: Nvidia GPU. Model inference (32 fp only) can run in cpu only.
|
11 |
+
|
12 |
+
## What's New
|
13 |
+
* Add [CARN Model (Fast, Accurate, and Lightweight Super-Resolution with Cascading Residual Network)](https://github.com/nmhkahn/CARN-pytorch). Model Codes are adapted from the authors's [github repo](https://github.com/nmhkahn/CARN-pytorch). I add [Spatial Channel Squeeze Excitation](https://arxiv.org/abs/1709.01507) and swap all 1x1 convolution with 3x3 standard convolutions. The model is trained in fp 16 with Nvidia's [apex](https://github.com/NVIDIA/apex). Details and plots on model variant can be found in [docs/CARN](./docs/CARN)
|
14 |
+
|
15 |
+
* Dilated Convolution seems less effective (if not make the model worse) in super resolution, though it brings some improvement in image segmentation, especially when dilated rate increases and then decreases. Further investigation is needed.
|
16 |
+
|
17 |
+
## How to Use
|
18 |
+
Compare the input image and upscaled image
|
19 |
+
```python
|
20 |
+
from utils.prepare_images import *
|
21 |
+
from Models import *
|
22 |
+
from torchvision.utils import save_image
|
23 |
+
model_cran_v2 = CARN_V2(color_channels=3, mid_channels=64, conv=nn.Conv2d,
|
24 |
+
single_conv_size=3, single_conv_group=1,
|
25 |
+
scale=2, activation=nn.LeakyReLU(0.1),
|
26 |
+
SEBlock=True, repeat_blocks=3, atrous=(1, 1, 1))
|
27 |
+
|
28 |
+
model_cran_v2 = network_to_half(model_cran_v2)
|
29 |
+
checkpoint = "model_check_points/CRAN_V2/CARN_model_checkpoint.pt"
|
30 |
+
model_cran_v2.load_state_dict(torch.load(checkpoint, 'cpu'))
|
31 |
+
# if use GPU, then comment out the next line so it can use fp16.
|
32 |
+
model_cran_v2 = model_cran_v2.float()
|
33 |
+
|
34 |
+
demo_img = "input_image.png"
|
35 |
+
img = Image.open(demo_img).convert("RGB")
|
36 |
+
|
37 |
+
# origin
|
38 |
+
img_t = to_tensor(img).unsqueeze(0)
|
39 |
+
|
40 |
+
# used to compare the origin
|
41 |
+
img = img.resize((img.size[0] // 2, img.size[1] // 2), Image.BICUBIC)
|
42 |
+
|
43 |
+
# overlapping split
|
44 |
+
# if input image is too large, then split it into overlapped patches
|
45 |
+
# details can be found at [here](https://github.com/nagadomi/waifu2x/issues/238)
|
46 |
+
img_splitter = ImageSplitter(seg_size=64, scale_factor=2, boarder_pad_size=3)
|
47 |
+
img_patches = img_splitter.split_img_tensor(img, scale_method=None, img_pad=0)
|
48 |
+
with torch.no_grad():
|
49 |
+
out = [model_cran_v2(i) for i in img_patches]
|
50 |
+
img_upscale = img_splitter.merge_img_tensor(out)
|
51 |
+
|
52 |
+
final = torch.cat([img_t, img_upscale])
|
53 |
+
save_image(final, 'out.png', nrow=2)
|
54 |
+
```
|
55 |
+
|
56 |
+
## Training
|
57 |
+
|
58 |
+
If possible, fp16 training is preferred because it is much faster with minimal quality decrease.
|
59 |
+
|
60 |
+
Sample training script is available in `train.py`, but you may need to change some liens.
|
61 |
+
|
62 |
+
### Image Processing
|
63 |
+
Original images are all at least 3k x 3K. I downsample them by LANCZOS so that one side has at most 2048, then I randomly cut them into 256x256 patches as target and use 128x128 with jpeg noise as input images. All input patches have at least 14 kb, and they are stored in SQLite with BLOB format. SQlite seems to have [better performance](https://www.sqlite.org/intern-v-extern-blob.html) than file system for small objects. H5 file format may not be optimal because of its larger size.
|
64 |
+
|
65 |
+
Although convolutions can take in any sizes of images, the content of image matters. For real life images, small patches may maintain color,brightness, etc variances in small regions, but for digital drawn images, colors are added in block areas. A small patch may end up showing entirely one color, and the model has little to learn.
|
66 |
+
|
67 |
+
For example, the following two plots come from CARN and have the same settings, including initial parameters. Both training loss and ssim are lower for 64x64, but they perform worse in test time compared to 128x128.
|
68 |
+
|
69 |
+
![loss](docs/CARN/plots/128_vs_64_model_loss.png)
|
70 |
+
![ssim](docs/CARN/plots/128_vs_64_model_ssim.png)
|
71 |
+
|
72 |
+
|
73 |
+
Downsampling methods are uniformly chosen among ```[PIL.Image.BILINEAR, PIL.Image.BICUBIC, PIL.Image.LANCZOS]``` , so different patches in the same image might be down-scaled in different ways.
|
74 |
+
|
75 |
+
Image noise are from JPEG format only. They are added by re-encoding PNG images into PIL's JPEG data with various quality. Noise level 1 means quality ranges uniformly from [75, 95]; level 2 means quality ranges uniformly from [50, 75].
|
76 |
+
|
77 |
+
|
78 |
+
## Models
|
79 |
+
Models are tuned and modified with extra features.
|
80 |
+
|
81 |
+
|
82 |
+
* [DCSCN 12](https://github.com/jiny2001/dcscn-super-resolution)
|
83 |
+
|
84 |
+
* [CRAN](https://github.com/nmhkahn/CARN-pytorch)
|
85 |
+
|
86 |
+
#### From [Waifu2x](https://github.com/nagadomi/waifu2x)
|
87 |
+
* [Upconv7](https://github.com/nagadomi/waifu2x/blob/7d156917ae1113ab847dab15c75db7642231e7fa/lib/srcnn.lua#L360)
|
88 |
+
|
89 |
+
* [Vgg_7](https://github.com/nagadomi/waifu2x/blob/7d156917ae1113ab847dab15c75db7642231e7fa/lib/srcnn.lua#L334)
|
90 |
+
|
91 |
+
* [Cascaded Residual U-Net with SEBlock](https://github.com/nagadomi/waifu2x/blob/7d156917ae1113ab847dab15c75db7642231e7fa/lib/srcnn.lua#L514) (PyTorch codes are not available and under testing)
|
92 |
+
|
93 |
+
#### Models Comparison
|
94 |
+
Images are from [Key: サマボケ(Summer Pocket)](http://key.visualarts.gr.jp/summer/).
|
95 |
+
|
96 |
+
The left column is the original image, and the right column is bicubic, DCSCN, CRAN_V2
|
97 |
+
|
98 |
+
![img](docs/demo_bicubic_model_comparison.png)
|
99 |
+
|
100 |
+
|
101 |
+
![img](docs/demo_true_bicubic_dcscn_upconv.png)
|
102 |
+
|
103 |
+
|
104 |
+
|
105 |
+
##### Scores
|
106 |
+
The list will be updated after I add more models.
|
107 |
+
|
108 |
+
Images are twitter icons (PNG) from [Key: サマボケ(Summer Pocket)](http://key.visualarts.gr.jp/summer/). They are cropped into non-overlapping 96x96 patches and down-scaled by 2. Then images are re-encoded into JPEG format with quality from [75, 95]. Scores are PSNR and MS-SSIM.
|
109 |
+
|
110 |
+
| | Total Parameters | BICUBIC | Random* |
|
111 |
+
| :---: | :---: | :---: | :---: |
|
112 |
+
| CRAN V2| 2,149,607 | 34.0985 (0.9924) | 34.0509 (0.9922) |
|
113 |
+
| DCSCN 12 |1,889,974 | 31.5358 (0.9851) | 31.1457 (0.9834) |
|
114 |
+
| Upconv 7| 552,480| 31.4566 (0.9788) | 30.9492 (0.9772) |
|
115 |
+
|
116 |
+
*uniformly select down scale methods from Image.BICUBIC, Image.BILINEAR, Image.LANCZOS.
|
117 |
+
|
118 |
+
|
119 |
+
|
120 |
+
|
121 |
+
|
122 |
+
#### DCSCN
|
123 |
+
[Fast and Accurate Image Super Resolution by Deep CNN with Skip Connection and Network in Network](https://github.com/jiny2001/dcscn-super-resolution#fast-and-accurate-image-super-resolution-by-deep-cnn-with-skip-connection-and-network-in-network)
|
124 |
+
|
125 |
+
DCSCN is very interesting as it has relatively quick forward computation, and both the shallow model (layerr 8) and deep model (layer 12) are quick to train. The settings are different from the paper.
|
126 |
+
|
127 |
+
* I use exponential decay to decrease the number of feature filters in each layer. [Here](https://github.com/jiny2001/dcscn-super-resolution/blob/a868775930c6b36922897b0203468f3f1481e935/DCSCN.py#L204) is the original filter decay method.
|
128 |
+
|
129 |
+
* I also increase the reconstruction filters from 48 to 128.
|
130 |
+
|
131 |
+
* All activations are replaced by SELU. Dropout and weight decay are not added neither because they significantly increase the training time.
|
132 |
+
|
133 |
+
* The loss function is changed from MSE to L1.
|
134 |
+
According to [Loss Functions for Image Restoration with Neural
|
135 |
+
Networks](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&cad=rja&uact=8&ved=0ahUKEwi7kuGt_7_bAhXrqVQKHRqhCcUQFghUMAM&url=http%3A%2F%2Fresearch.nvidia.com%2Fsites%2Fdefault%2Ffiles%2Fpubs%2F2017-03_Loss-Functions-for%2Fcomparison_tci.pdf&usg=AOvVaw1p0ndOKRH2ZaEsumO7d_bA), L1 seems to be more robust and converges faster than MSE. But the authors find the results from L1 and MSE are [similar](https://github.com/jiny2001/dcscn-super-resolution/issues/29).
|
136 |
+
|
137 |
+
|
138 |
+
I need to thank jiny2001 (one of the paper's author) to test the difference of SELU and PRELU. SELU seems more stable and has fewer parameters to train. It is a good drop in replacement
|
139 |
+
>layers=8, filters=96 and dataset=yang91+bsd200.
|
140 |
+
![](docs/DCSCN_comparison/selu_prelu.png)
|
141 |
+
The details can be found in [here]( https://github.com/jiny2001/dcscn-super-resolution/issues/29).
|
142 |
+
|
143 |
+
|
144 |
+
|
145 |
+
A pre-trained 12-layer model as well as model parameters are available. The model run time is around 3-5 times of Waifu2x. The output quality is usually visually indistinguishable, but its PSNR and SSIM are bit higher. Though, such comparison is not fair since the 12-layer model has around 1,889,974 parameters, 5 times more than waifu2x's Upconv_7 model.
|
146 |
+
|
147 |
+
#### CARN
|
148 |
+
Channels are set to 64 across all blocks, so residual adds are very effective. Increase the channels to 128 lower the loss curve a little bit but doubles the total parameters from 0.9 Millions to 3 Millions. 32 Channels has much worse performance. Increasing the number of cascaded blocks from 3 to 5 doesn't lower the loss a lot.
|
149 |
+
|
150 |
+
SE Blocks seems to have the most obvious improvement without increasing the computation a lot. Partial based padding seems have little effect if not decrease the quality. Atrous convolution is slower about 10%-20% than normal convolution in Pytorch 1.0, but there are no obvious improvement.
|
151 |
+
|
152 |
+
Another more effective model is to add upscaled input image to the final convolution. A simple bilinear upscaled image seems sufficient.
|
153 |
+
|
154 |
+
More examples on model configurations can be found in [docs/CARN folder](./docs/CARN/carn_plot_loss.md)
|
155 |
+
|
156 |
+
![img](docs/CARN/plots/CARN_Compare.png)
|
157 |
+
|
158 |
+
![img](docs/CARN/plots/CARN_Compare_Res_Add.png)
|
159 |
+
|
160 |
+
### Waifu2x Original Models
|
161 |
+
Models can load waifu2x's pre-trained weights. The function ```forward_checkpoint``` sets the ```nn.LeakyReLU``` to compute data inplace.
|
162 |
+
|
163 |
+
#### Upconv_7
|
164 |
+
Original waifu2x's model. PyTorch's implementation with cpu only is around 5 times longer for large images. The output images have very close PSNR and SSIM scores compared to images generated from the [caffe version](https://github.com/lltcggie/waifu2x-caffe) , thought they are not identical.
|
165 |
+
|
166 |
+
#### Vgg_7
|
167 |
+
Not tested yet, but it is ready to use.
|
Waifu2x/__init__.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
# file: __init__.py
|
3 |
+
# time: 05/12/2022
|
4 |
+
# author: yangheng <hy345@exeter.ac.uk>
|
5 |
+
# github: https://github.com/yangheng95
|
6 |
+
# huggingface: https://huggingface.co/yangheng
|
7 |
+
# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en
|
8 |
+
# Copyright (C) 2021. All Rights Reserved.
|
9 |
+
from .magnify import ImageMagnifier
|
Waifu2x/magnify.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
# file: test.py
|
3 |
+
# time: 05/12/2022
|
4 |
+
# author: yangheng <hy345@exeter.ac.uk>
|
5 |
+
# github: https://github.com/yangheng95
|
6 |
+
# huggingface: https://huggingface.co/yangheng
|
7 |
+
# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en
|
8 |
+
# Copyright (C) 2021. All Rights Reserved.
|
9 |
+
from pathlib import Path
|
10 |
+
from typing import Union
|
11 |
+
|
12 |
+
import autocuda
|
13 |
+
import findfile
|
14 |
+
from pyabsa.utils.pyabsa_utils import fprint
|
15 |
+
from torchvision import transforms
|
16 |
+
from .utils.prepare_images import *
|
17 |
+
from .Models import *
|
18 |
+
|
19 |
+
|
20 |
+
class ImageMagnifier:
|
21 |
+
|
22 |
+
def __init__(self):
|
23 |
+
self.device = autocuda.auto_cuda()
|
24 |
+
self.model_cran_v2 = CARN_V2(color_channels=3, mid_channels=64, conv=nn.Conv2d,
|
25 |
+
single_conv_size=3, single_conv_group=1,
|
26 |
+
scale=2, activation=nn.LeakyReLU(0.1),
|
27 |
+
SEBlock=True, repeat_blocks=3, atrous=(1, 1, 1))
|
28 |
+
|
29 |
+
self.model_cran_v2 = network_to_half(self.model_cran_v2)
|
30 |
+
self.checkpoint = findfile.find_cwd_file("CARN_model_checkpoint.pt")
|
31 |
+
self.model_cran_v2.load_state_dict(torch.load(self.checkpoint, map_location='cpu'))
|
32 |
+
# if use GPU, then comment out the next line so it can use fp16.
|
33 |
+
self.model_cran_v2 = self.model_cran_v2.float().to(self.device)
|
34 |
+
self.model_cran_v2.to(self.device)
|
35 |
+
|
36 |
+
def __image_scale(self, img, scale_factor: int = 2):
|
37 |
+
img_splitter = ImageSplitter(seg_size=64, scale_factor=scale_factor, boarder_pad_size=3)
|
38 |
+
img_patches = img_splitter.split_img_tensor(img, scale_method=None, img_pad=0)
|
39 |
+
with torch.no_grad():
|
40 |
+
if self.device != 'cpu':
|
41 |
+
with torch.cuda.amp.autocast():
|
42 |
+
out = [self.model_cran_v2(i.to(self.device)) for i in img_patches]
|
43 |
+
else:
|
44 |
+
with torch.cpu.amp.autocast():
|
45 |
+
out = [self.model_cran_v2(i) for i in img_patches]
|
46 |
+
img_upscale = img_splitter.merge_img_tensor(out)
|
47 |
+
|
48 |
+
final = torch.cat([img_upscale])
|
49 |
+
|
50 |
+
return transforms.ToPILImage()(final[0])
|
51 |
+
|
52 |
+
def magnify(self, img, scale_factor: int = 2):
|
53 |
+
fprint("scale factor reset to:", scale_factor//2*2)
|
54 |
+
_scale_factor = scale_factor
|
55 |
+
while _scale_factor // 2 > 0:
|
56 |
+
img = self.__image_scale(img, scale_factor=2)
|
57 |
+
_scale_factor = _scale_factor // 2
|
58 |
+
return img
|
59 |
+
|
60 |
+
def magnify_from_file(self, img_path: Union[str, Path], scale_factor: int = 2, save_img: bool = True):
|
61 |
+
|
62 |
+
if not os.path.exists(img_path):
|
63 |
+
raise FileNotFoundError("Path is not found.")
|
64 |
+
if os.path.isfile(img_path):
|
65 |
+
try:
|
66 |
+
img = Image.open(img_path)
|
67 |
+
img = self.magnify(img, scale_factor)
|
68 |
+
if save_img:
|
69 |
+
img.save(os.path.join(img_path))
|
70 |
+
except Exception as e:
|
71 |
+
fprint(img_path, e)
|
72 |
+
fprint(img_path, "Done.")
|
73 |
+
|
74 |
+
elif os.path.isdir(img_path):
|
75 |
+
for path in os.listdir(img_path):
|
76 |
+
try:
|
77 |
+
img = Image.open(os.path.join(img_path, path))
|
78 |
+
img = self.magnify(img, scale_factor)
|
79 |
+
if save_img:
|
80 |
+
img.save(os.path.join(img_path, path))
|
81 |
+
except Exception as e:
|
82 |
+
fprint(path, e)
|
83 |
+
continue
|
84 |
+
fprint(path, "Done.")
|
85 |
+
else:
|
86 |
+
raise TypeError("Path is not a file or directory.")
|
Waifu2x/model_check_points/CRAN_V2/CARN_adam_checkpoint.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:292f2be9ea173861e4a7f6cf580f04fe9a1fc6c78fdac6f182cbc051ea50791e
|
3 |
+
size 31734614
|
Waifu2x/model_check_points/CRAN_V2/CARN_model_checkpoint.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3a0ef4fdea5b0b2a91b05b7a39fe63df3e27e1d18df477065e7f268a7feaaad2
|
3 |
+
size 4329165
|
Waifu2x/model_check_points/CRAN_V2/CARN_scheduler_last_iter.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ba2302e523d32bfeb9b542a9dc6aa5ecdb45babc793892153245d6c69ae23433
|
3 |
+
size 151
|
Waifu2x/model_check_points/CRAN_V2/CRAN_V2_02_28_2019.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b74e163d829f6f587e3fdb0b645342e494416accb1962cf0973354de5ec157ea
|
3 |
+
size 49895595
|
Waifu2x/model_check_points/CRAN_V2/ReadME.md
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Model Specifications
|
2 |
+
|
3 |
+
|
4 |
+
```python
|
5 |
+
model_cran_v2 = CARN_V2(color_channels=3, mid_channels=64, conv=nn.Conv2d,
|
6 |
+
single_conv_size=3, single_conv_group=1,
|
7 |
+
scale=2, activation=nn.LeakyReLU(0.1),
|
8 |
+
SEBlock=True, repeat_blocks=3, atrous=(1, 1, 1))
|
9 |
+
|
10 |
+
model_cran_v2 = network_to_half(model_cran_v2)
|
11 |
+
checkpoint = "CARN_model_checkpoint.pt"
|
12 |
+
model_cran_v2.load_state_dict(torch.load(checkpoint, 'cpu'))
|
13 |
+
model_cran_v2 = model_cran_v2.float() # if use cpu
|
14 |
+
|
15 |
+
````
|
16 |
+
|
17 |
+
To use pre-trained model for training
|
18 |
+
|
19 |
+
```python
|
20 |
+
|
21 |
+
model = CARN_V2(color_channels=3, mid_channels=64, conv=nn.Conv2d,
|
22 |
+
single_conv_size=3, single_conv_group=1,
|
23 |
+
scale=2, activation=nn.LeakyReLU(0.1),
|
24 |
+
SEBlock=True, repeat_blocks=3, atrous=(1, 1, 1))
|
25 |
+
|
26 |
+
model = network_to_half(model)
|
27 |
+
model = model.cuda()
|
28 |
+
model.load_state_dict(torch.load("CARN_model_checkpoint.pt"))
|
29 |
+
|
30 |
+
learning_rate = 1e-4
|
31 |
+
weight_decay = 1e-6
|
32 |
+
optimizer = optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay, amsgrad=True)
|
33 |
+
optimizer = FP16_Optimizer(optimizer, static_loss_scale=128.0, verbose=False)
|
34 |
+
optimizer.load_state_dict(torch.load("CARN_adam_checkpoint.pt"))
|
35 |
+
|
36 |
+
last_iter = torch.load("CARN_scheduler_last_iter") # -1 if start from new
|
37 |
+
scheduler = CyclicLR(optimizer.optimizer, base_lr=1e-4, max_lr=4e-4,
|
38 |
+
step_size=3 * total_batch, mode="triangular",
|
39 |
+
last_batch_iteration=last_iter)
|
40 |
+
|
41 |
+
```
|
Waifu2x/model_check_points/CRAN_V2/test_loss.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:93f644a6a3f6636035980855f56ef3dbc8784679371b06b81e0e4d06067c142d
|
3 |
+
size 43507
|
Waifu2x/model_check_points/CRAN_V2/test_psnr.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ae8f8d1a3d175e76dcbcdcf0cede898e8f2cf169f3eec14eeb75a4e19d8e2d6b
|
3 |
+
size 42563
|
Waifu2x/model_check_points/CRAN_V2/test_ssim.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:763ff936f536b12b37b351c09f3c1290fb2188399aea3d9ce3cf069bd0d135e7
|
3 |
+
size 43515
|
Waifu2x/model_check_points/CRAN_V2/train_loss.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:85a86e94cd689adff04c4b22bf2534d17aa52af5e7309a82bc2a4f5c6c144900
|
3 |
+
size 15564175
|
Waifu2x/model_check_points/CRAN_V2/train_psnr.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2d1e88646b74a054ddf20ba41368a01162e35d9c88ac72f392a6ba08a5c7ef3b
|
3 |
+
size 15564175
|
Waifu2x/model_check_points/CRAN_V2/train_ssim.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6b8da8bc73f64997c5b2d15d6161b11dbd172258a62c88572c032feb73bd022b
|
3 |
+
size 15564175
|
Waifu2x/model_check_points/ReadME.md
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Resume & Use Model Check Points
|
2 |
+
|
3 |
+
This folder contains check points for models and their weights. They are generated from [PyTorch's pickle](https://pytorch.org/docs/master/notes/serialization.html).
|
4 |
+
|
5 |
+
Model specifications are in each folder's ReadME.
|
6 |
+
|
7 |
+
Pickle names with "model" contain the entire models, and they can be used as an freeze module by calling the "forward_checkpoint" function to generate images.
|
8 |
+
|
9 |
+
Example:
|
10 |
+
```python
|
11 |
+
import torch
|
12 |
+
# No need to reconstruct the model
|
13 |
+
model = torch.load("./DCSCN/DCSCN_model_387epos_L12_noise_1.pt")
|
14 |
+
x = torch.randn((1,3,10,10)), torch.randn((1,3,20,20))
|
15 |
+
out = model.forward_checkpoint(a)
|
16 |
+
```
|
17 |
+
|
18 |
+
Pickle names with "weights" are model weights, and they are named dictionaries.
|
19 |
+
|
20 |
+
Example:
|
21 |
+
```python
|
22 |
+
model = DCSCN(*) # the setting must be the same to load check points weights.
|
23 |
+
model.load_state_dict(torch.load("./DCSCN/DCSCN_weights_387epos_L12_noise_1.pt"))
|
24 |
+
# then you can resume the model training
|
25 |
+
```
|
26 |
+
|
27 |
+
Model check poins in Upconv_7 and vgg_7 are from [waifu2x's repo](https://github.com/nagadomi/waifu2x/tree/master/models). To load weights into a model, please use ```load_pre_train_weights``` function.
|
28 |
+
|
29 |
+
Example:
|
30 |
+
```python
|
31 |
+
model = UpConv_7()
|
32 |
+
model.load_pre_train_weights(json_file=...)
|
33 |
+
# then the model is ready to use
|
34 |
+
```
|
Waifu2x/train.py
ADDED
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from torch import optim
|
3 |
+
from torch.utils.data import DataLoader
|
4 |
+
from torchvision.utils import save_image
|
5 |
+
from tqdm import trange
|
6 |
+
|
7 |
+
from Dataloader import *
|
8 |
+
from .utils import image_quality
|
9 |
+
from .utils.cls import CyclicLR
|
10 |
+
from .utils.prepare_images import *
|
11 |
+
|
12 |
+
train_folder = './dataset/train'
|
13 |
+
test_folder = "./dataset/test"
|
14 |
+
|
15 |
+
img_dataset = ImageDBData(db_file='dataset/images.db', db_table="train_images_size_128_noise_1_rgb", max_images=24)
|
16 |
+
img_data = DataLoader(img_dataset, batch_size=6, shuffle=True, num_workers=6)
|
17 |
+
|
18 |
+
total_batch = len(img_data)
|
19 |
+
print(len(img_dataset))
|
20 |
+
|
21 |
+
test_dataset = ImageDBData(db_file='dataset/test2.db', db_table="test_images_size_128_noise_1_rgb", max_images=None)
|
22 |
+
num_test = len(test_dataset)
|
23 |
+
test_data = DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=1)
|
24 |
+
|
25 |
+
criteria = nn.L1Loss()
|
26 |
+
|
27 |
+
model = CARN_V2(color_channels=3, mid_channels=64, conv=nn.Conv2d,
|
28 |
+
single_conv_size=3, single_conv_group=1,
|
29 |
+
scale=2, activation=nn.LeakyReLU(0.1),
|
30 |
+
SEBlock=True, repeat_blocks=3, atrous=(1, 1, 1))
|
31 |
+
|
32 |
+
model.total_parameters()
|
33 |
+
|
34 |
+
|
35 |
+
# model.initialize_weights_xavier_uniform()
|
36 |
+
|
37 |
+
# fp16 training is available in GPU only
|
38 |
+
model = network_to_half(model)
|
39 |
+
model = model.cuda()
|
40 |
+
model.load_state_dict(torch.load("CARN_model_checkpoint.pt"))
|
41 |
+
|
42 |
+
learning_rate = 1e-4
|
43 |
+
weight_decay = 1e-6
|
44 |
+
optimizer = optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay, amsgrad=True)
|
45 |
+
# optimizer = optim.SGD(model.parameters(), momentum=0.9, nesterov=True, weight_decay=weight_decay, lr=learning_rate)
|
46 |
+
|
47 |
+
# optimizer = FP16_Optimizer(optimizer, static_loss_scale=128.0, verbose=False)
|
48 |
+
# optimizer.load_state_dict(torch.load("CARN_adam_checkpoint.pt"))
|
49 |
+
|
50 |
+
last_iter = -1 # torch.load("CARN_scheduler_last_iter")
|
51 |
+
scheduler = CyclicLR(optimizer, base_lr=1e-4, max_lr=1e-4,
|
52 |
+
step_size=3 * total_batch, mode="triangular",
|
53 |
+
last_batch_iteration=last_iter)
|
54 |
+
train_loss = []
|
55 |
+
train_ssim = []
|
56 |
+
train_psnr = []
|
57 |
+
|
58 |
+
test_loss = []
|
59 |
+
test_ssim = []
|
60 |
+
test_psnr = []
|
61 |
+
|
62 |
+
# train_loss = torch.load("train_loss.pt")
|
63 |
+
# train_ssim = torch.load("train_ssim.pt")
|
64 |
+
# train_psnr = torch.load("train_psnr.pt")
|
65 |
+
#
|
66 |
+
# test_loss = torch.load("test_loss.pt")
|
67 |
+
# test_ssim = torch.load("test_ssim.pt")
|
68 |
+
# test_psnr = torch.load("test_psnr.pt")
|
69 |
+
|
70 |
+
|
71 |
+
counter = 0
|
72 |
+
iteration = 2
|
73 |
+
ibar = trange(iteration, ascii=True, maxinterval=1, postfix={"avg_loss": 0, "train_ssim": 0, "test_ssim": 0})
|
74 |
+
for i in ibar:
|
75 |
+
# batch_loss = []
|
76 |
+
# insample_ssim = []
|
77 |
+
# insample_psnr = []
|
78 |
+
for index, batch in enumerate(img_data):
|
79 |
+
scheduler.batch_step()
|
80 |
+
lr_img, hr_img = batch
|
81 |
+
lr_img = lr_img.cuda().half()
|
82 |
+
hr_img = hr_img.cuda()
|
83 |
+
|
84 |
+
# model.zero_grad()
|
85 |
+
optimizer.zero_grad()
|
86 |
+
outputs = model.forward(lr_img)
|
87 |
+
outputs = outputs.float()
|
88 |
+
loss = criteria(outputs, hr_img)
|
89 |
+
# loss.backward()
|
90 |
+
optimizer.backward(loss)
|
91 |
+
# nn.utils.clip_grad_norm_(model.parameters(), 5)
|
92 |
+
optimizer.step()
|
93 |
+
|
94 |
+
counter += 1
|
95 |
+
# train_loss.append(loss.item())
|
96 |
+
|
97 |
+
ssim = image_quality.msssim(outputs, hr_img).item()
|
98 |
+
psnr = image_quality.psnr(outputs, hr_img).item()
|
99 |
+
|
100 |
+
ibar.set_postfix(ratio=index / total_batch, loss=loss.item(),
|
101 |
+
ssim=ssim, batch=index,
|
102 |
+
psnr=psnr,
|
103 |
+
lr=scheduler.current_lr
|
104 |
+
)
|
105 |
+
train_loss.append(loss.item())
|
106 |
+
train_ssim.append(ssim)
|
107 |
+
train_psnr.append(psnr)
|
108 |
+
|
109 |
+
# +++++++++++++++++++++++++++++++++++++
|
110 |
+
# save checkpoints by iterations
|
111 |
+
# -------------------------------------
|
112 |
+
|
113 |
+
if (counter + 1) % 500 == 0:
|
114 |
+
torch.save(model.state_dict(), 'CARN_model_checkpoint.pt')
|
115 |
+
torch.save(optimizer.state_dict(), 'CARN_adam_checkpoint.pt')
|
116 |
+
torch.save(train_loss, 'train_loss.pt')
|
117 |
+
torch.save(train_ssim, "train_ssim.pt")
|
118 |
+
torch.save(train_psnr, 'train_psnr.pt')
|
119 |
+
torch.save(scheduler.last_batch_iteration, "CARN_scheduler_last_iter.pt")
|
120 |
+
|
121 |
+
# +++++++++++++++++++++++++++++++++++++
|
122 |
+
# End of One Epoch
|
123 |
+
# -------------------------------------
|
124 |
+
|
125 |
+
# one_ite_loss = np.mean(batch_loss)
|
126 |
+
# one_ite_ssim = np.mean(insample_ssim)
|
127 |
+
# one_ite_psnr = np.mean(insample_psnr)
|
128 |
+
|
129 |
+
# print(f"One iteration loss {one_ite_loss}, ssim {one_ite_ssim}, psnr {one_ite_psnr}")
|
130 |
+
# train_loss.append(one_ite_loss)
|
131 |
+
# train_ssim.append(one_ite_ssim)
|
132 |
+
# train_psnr.append(one_ite_psnr)
|
133 |
+
|
134 |
+
torch.save(model.state_dict(), 'CARN_model_checkpoint.pt')
|
135 |
+
# torch.save(scheduler, "CARN_scheduler_optim.pt")
|
136 |
+
torch.save(optimizer.state_dict(), 'CARN_adam_checkpoint.pt')
|
137 |
+
torch.save(train_loss, 'train_loss.pt')
|
138 |
+
torch.save(train_ssim, "train_ssim.pt")
|
139 |
+
torch.save(train_psnr, 'train_psnr.pt')
|
140 |
+
# torch.save(scheduler.last_batch_iteration, "CARN_scheduler_last_iter.pt")
|
141 |
+
|
142 |
+
# +++++++++++++++++++++++++++++++++++++
|
143 |
+
# Test
|
144 |
+
# -------------------------------------
|
145 |
+
|
146 |
+
with torch.no_grad():
|
147 |
+
ssim = []
|
148 |
+
batch_loss = []
|
149 |
+
psnr = []
|
150 |
+
for index, test_batch in enumerate(test_data):
|
151 |
+
lr_img, hr_img = test_batch
|
152 |
+
lr_img = lr_img.cuda()
|
153 |
+
hr_img = hr_img.cuda()
|
154 |
+
|
155 |
+
lr_img_up = model(lr_img)
|
156 |
+
lr_img_up = lr_img_up.float()
|
157 |
+
loss = criteria(lr_img_up, hr_img)
|
158 |
+
|
159 |
+
save_image([lr_img_up[0], hr_img[0]], f"check_test_imgs/{index}.png")
|
160 |
+
batch_loss.append(loss.item())
|
161 |
+
ssim.append(image_quality.msssim(lr_img_up, hr_img).item())
|
162 |
+
psnr.append(image_quality.psnr(lr_img_up, hr_img).item())
|
163 |
+
|
164 |
+
test_ssim.append(np.mean(ssim))
|
165 |
+
test_loss.append(np.mean(batch_loss))
|
166 |
+
test_psnr.append(np.mean(psnr))
|
167 |
+
|
168 |
+
torch.save(test_loss, 'test_loss.pt')
|
169 |
+
torch.save(test_ssim, "test_ssim.pt")
|
170 |
+
torch.save(test_psnr, "test_psnr.pt")
|
171 |
+
|
172 |
+
# import subprocess
|
173 |
+
|
174 |
+
# subprocess.call(["shutdown", "/s"])
|
Waifu2x/utils/Img_to_H5.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import glob
|
2 |
+
|
3 |
+
import h5py
|
4 |
+
from PIL import Image
|
5 |
+
from torchvision.transforms import RandomCrop
|
6 |
+
from torchvision.transforms.functional import to_tensor
|
7 |
+
from tqdm import tqdm
|
8 |
+
|
9 |
+
from Dataloader import ImageAugment
|
10 |
+
|
11 |
+
patch_size = 128
|
12 |
+
shrink_size = 2
|
13 |
+
noise_level = 1
|
14 |
+
patches_per_img = 20
|
15 |
+
images = glob.glob("dataset/train/*")
|
16 |
+
|
17 |
+
database = h5py.File("train_images.hdf5", 'w')
|
18 |
+
|
19 |
+
dat_group = database.create_group("shrink_2_noise_level_1_downsample_random_rgb")
|
20 |
+
# del database['shrink_2_noise_level_1_downsample_random']
|
21 |
+
storage_lr = dat_group.create_dataset("train_lr", shape=(patches_per_img * len(images), 3,
|
22 |
+
patch_size // shrink_size,
|
23 |
+
patch_size // shrink_size),
|
24 |
+
dtype='float32',
|
25 |
+
# compression='lzf',
|
26 |
+
)
|
27 |
+
storage_hr = dat_group.create_dataset("train_hr", shape=(patches_per_img * len(images), 3,
|
28 |
+
patch_size, patch_size),
|
29 |
+
# compression='lzf',
|
30 |
+
dtype='float32')
|
31 |
+
|
32 |
+
random_cropper = RandomCrop(size=patch_size)
|
33 |
+
img_augmenter = ImageAugment(shrink_size, noise_level, down_sample_method=None)
|
34 |
+
|
35 |
+
|
36 |
+
def get_img_patches(img_pil):
|
37 |
+
img_patch = random_cropper(img_pil)
|
38 |
+
lr_hr_patches = img_augmenter.process(img_patch)
|
39 |
+
return lr_hr_patches
|
40 |
+
|
41 |
+
|
42 |
+
counter = 0
|
43 |
+
for img in tqdm(images):
|
44 |
+
img_pil = Image.open(img).convert("RGB")
|
45 |
+
for i in range(patches_per_img):
|
46 |
+
patch = get_img_patches(img_pil)
|
47 |
+
storage_lr[counter] = to_tensor(patch[0].convert("RGB")).numpy()
|
48 |
+
storage_hr[counter] = to_tensor(patch[1].convert("RGB")).numpy()
|
49 |
+
counter += 1
|
50 |
+
database.close()
|
Waifu2x/utils/__init__.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
# file: __init__.py
|
3 |
+
# time: 05/12/2022
|
4 |
+
# author: yangheng <hy345@exeter.ac.uk>
|
5 |
+
# github: https://github.com/yangheng95
|
6 |
+
# huggingface: https://huggingface.co/yangheng
|
7 |
+
# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en
|
8 |
+
# Copyright (C) 2021. All Rights Reserved.
|
Waifu2x/utils/cls.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This code is copied from https://github.com/thomasjpfan/pytorch/blob/401ec389db2c9d2978917a6e4d1101b20340d7e7/torch/optim/lr_scheduler.py
|
2 |
+
|
3 |
+
|
4 |
+
# This code is under review at PyTorch and is to be merged eventually to make CLR available to all.
|
5 |
+
# Tested with pytorch 0.2.0
|
6 |
+
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
|
10 |
+
class CyclicLR(object):
|
11 |
+
"""Sets the learning rate of each parameter group according to
|
12 |
+
cyclical learning rate policy (CLR). The policy cycles the learning
|
13 |
+
rate between two boundaries with a constant frequency, as detailed in
|
14 |
+
the paper `Cyclical Learning Rates for Training Neural Networks`_.
|
15 |
+
The distance between the two boundaries can be scaled on a per-iteration
|
16 |
+
or per-cycle basis.
|
17 |
+
Cyclical learning rate policy changes the learning rate after every batch.
|
18 |
+
`batch_step` should be called after a batch has been used for training.
|
19 |
+
To resume training, save `last_batch_iteration` and use it to instantiate `CycleLR`.
|
20 |
+
This class has three built-in policies, as put forth in the paper:
|
21 |
+
"triangular":
|
22 |
+
A basic triangular cycle w/ no amplitude scaling.
|
23 |
+
"triangular2":
|
24 |
+
A basic triangular cycle that scales initial amplitude by half each cycle.
|
25 |
+
"exp_range":
|
26 |
+
A cycle that scales initial amplitude by gamma**(cycle iterations) at each
|
27 |
+
cycle iteration.
|
28 |
+
This implementation was adapted from the github repo: `bckenstler/CLR`_
|
29 |
+
Args:
|
30 |
+
optimizer (Optimizer): Wrapped optimizer.
|
31 |
+
base_lr (float or list): Initial learning rate which is the
|
32 |
+
lower boundary in the cycle for eachparam groups.
|
33 |
+
Default: 0.001
|
34 |
+
max_lr (float or list): Upper boundaries in the cycle for
|
35 |
+
each parameter group. Functionally,
|
36 |
+
it defines the cycle amplitude (max_lr - base_lr).
|
37 |
+
The lr at any cycle is the sum of base_lr
|
38 |
+
and some scaling of the amplitude; therefore
|
39 |
+
max_lr may not actually be reached depending on
|
40 |
+
scaling function. Default: 0.006
|
41 |
+
step_size (int): Number of training iterations per
|
42 |
+
half cycle. Authors suggest setting step_size
|
43 |
+
2-8 x training iterations in epoch. Default: 2000
|
44 |
+
mode (str): One of {triangular, triangular2, exp_range}.
|
45 |
+
Values correspond to policies detailed above.
|
46 |
+
If scale_fn is not None, this argument is ignored.
|
47 |
+
Default: 'triangular'
|
48 |
+
gamma (float): Constant in 'exp_range' scaling function:
|
49 |
+
gamma**(cycle iterations)
|
50 |
+
Default: 1.0
|
51 |
+
scale_fn (function): Custom scaling policy defined by a single
|
52 |
+
argument lambda function, where
|
53 |
+
0 <= scale_fn(x) <= 1 for all x >= 0.
|
54 |
+
mode paramater is ignored
|
55 |
+
Default: None
|
56 |
+
scale_mode (str): {'cycle', 'iterations'}.
|
57 |
+
Defines whether scale_fn is evaluated on
|
58 |
+
cycle number or cycle iterations (training
|
59 |
+
iterations since start of cycle).
|
60 |
+
Default: 'cycle'
|
61 |
+
last_batch_iteration (int): The index of the last batch. Default: -1
|
62 |
+
Example:
|
63 |
+
>>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
|
64 |
+
>>> scheduler = torch.optim.CyclicLR(optimizer)
|
65 |
+
>>> data_loader = torch.utils.data.DataLoader(...)
|
66 |
+
>>> for epoch in range(10):
|
67 |
+
>>> for batch in data_loader:
|
68 |
+
>>> scheduler.batch_step()
|
69 |
+
>>> train_batch(...)
|
70 |
+
.. _Cyclical Learning Rates for Training Neural Networks: https://arxiv.org/abs/1506.01186
|
71 |
+
.. _bckenstler/CLR: https://github.com/bckenstler/CLR
|
72 |
+
"""
|
73 |
+
|
74 |
+
def __init__(self, optimizer, base_lr=1e-3, max_lr=6e-3,
|
75 |
+
step_size=2000, mode='triangular', gamma=1.,
|
76 |
+
scale_fn=None, scale_mode='cycle', last_batch_iteration=-1):
|
77 |
+
|
78 |
+
# if not isinstance(optimizer, Optimizer):
|
79 |
+
# raise TypeError('{} is not an Optimizer'.format(
|
80 |
+
# type(optimizer).__name__))
|
81 |
+
self.optimizer = optimizer
|
82 |
+
|
83 |
+
if isinstance(base_lr, list) or isinstance(base_lr, tuple):
|
84 |
+
if len(base_lr) != len(optimizer.param_groups):
|
85 |
+
raise ValueError("expected {} base_lr, got {}".format(
|
86 |
+
len(optimizer.param_groups), len(base_lr)))
|
87 |
+
self.base_lrs = list(base_lr)
|
88 |
+
else:
|
89 |
+
self.base_lrs = [base_lr] * len(optimizer.param_groups)
|
90 |
+
|
91 |
+
if isinstance(max_lr, list) or isinstance(max_lr, tuple):
|
92 |
+
if len(max_lr) != len(optimizer.param_groups):
|
93 |
+
raise ValueError("expected {} max_lr, got {}".format(
|
94 |
+
len(optimizer.param_groups), len(max_lr)))
|
95 |
+
self.max_lrs = list(max_lr)
|
96 |
+
else:
|
97 |
+
self.max_lrs = [max_lr] * len(optimizer.param_groups)
|
98 |
+
|
99 |
+
self.step_size = step_size
|
100 |
+
|
101 |
+
if mode not in ['triangular', 'triangular2', 'exp_range'] \
|
102 |
+
and scale_fn is None:
|
103 |
+
raise ValueError('mode is invalid and scale_fn is None')
|
104 |
+
|
105 |
+
self.mode = mode
|
106 |
+
self.gamma = gamma
|
107 |
+
self.current_lr = None
|
108 |
+
|
109 |
+
if scale_fn is None:
|
110 |
+
if self.mode == 'triangular':
|
111 |
+
self.scale_fn = self._triangular_scale_fn
|
112 |
+
self.scale_mode = 'cycle'
|
113 |
+
elif self.mode == 'triangular2':
|
114 |
+
self.scale_fn = self._triangular2_scale_fn
|
115 |
+
self.scale_mode = 'cycle'
|
116 |
+
elif self.mode == 'exp_range':
|
117 |
+
self.scale_fn = self._exp_range_scale_fn
|
118 |
+
self.scale_mode = 'iterations'
|
119 |
+
else:
|
120 |
+
self.scale_fn = scale_fn
|
121 |
+
self.scale_mode = scale_mode
|
122 |
+
|
123 |
+
self.batch_step(last_batch_iteration + 1)
|
124 |
+
self.last_batch_iteration = last_batch_iteration
|
125 |
+
|
126 |
+
def batch_step(self, batch_iteration=None):
|
127 |
+
if batch_iteration is None:
|
128 |
+
batch_iteration = self.last_batch_iteration + 1
|
129 |
+
self.last_batch_iteration = batch_iteration
|
130 |
+
for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()):
|
131 |
+
param_group['lr'] = lr
|
132 |
+
self.current_lr = lr
|
133 |
+
|
134 |
+
def _triangular_scale_fn(self, x):
|
135 |
+
return 1.
|
136 |
+
|
137 |
+
def _triangular2_scale_fn(self, x):
|
138 |
+
return 1 / (2. ** (x - 1))
|
139 |
+
|
140 |
+
def _exp_range_scale_fn(self, x):
|
141 |
+
return self.gamma ** (x)
|
142 |
+
|
143 |
+
def get_lr(self):
|
144 |
+
step_size = float(self.step_size)
|
145 |
+
cycle = np.floor(1 + self.last_batch_iteration / (2 * step_size))
|
146 |
+
x = np.abs(self.last_batch_iteration / step_size - 2 * cycle + 1)
|
147 |
+
|
148 |
+
lrs = []
|
149 |
+
param_lrs = zip(self.optimizer.param_groups, self.base_lrs, self.max_lrs)
|
150 |
+
for param_group, base_lr, max_lr in param_lrs:
|
151 |
+
base_height = (max_lr - base_lr) * np.maximum(0, (1 - x))
|
152 |
+
if self.scale_mode == 'cycle':
|
153 |
+
lr = base_lr + base_height * self.scale_fn(cycle)
|
154 |
+
else:
|
155 |
+
lr = base_lr + base_height * self.scale_fn(self.last_batch_iteration)
|
156 |
+
lrs.append(lr)
|
157 |
+
return lrs
|
Waifu2x/utils/image_quality.py
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Pytorch Multi-Scale Structural Similarity Index (SSIM)
|
2 |
+
# This code is written by jorge-pessoa (https://github.com/jorge-pessoa/pytorch-msssim)
|
3 |
+
# MIT licence
|
4 |
+
import math
|
5 |
+
from math import exp
|
6 |
+
|
7 |
+
import torch
|
8 |
+
import torch.nn.functional as F
|
9 |
+
from torch.autograd import Variable
|
10 |
+
|
11 |
+
|
12 |
+
# +++++++++++++++++++++++++++++++++++++
|
13 |
+
# SSIM
|
14 |
+
# -------------------------------------
|
15 |
+
|
16 |
+
def gaussian(window_size, sigma):
|
17 |
+
gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])
|
18 |
+
return gauss / gauss.sum()
|
19 |
+
|
20 |
+
|
21 |
+
def create_window(window_size, channel):
|
22 |
+
_1D_window = gaussian(window_size, 1.5).unsqueeze(1)
|
23 |
+
_2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
|
24 |
+
window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())
|
25 |
+
return window
|
26 |
+
|
27 |
+
|
28 |
+
def _ssim(img1, img2, window, window_size, channel, size_average=True, full=False):
|
29 |
+
padd = 0
|
30 |
+
|
31 |
+
mu1 = F.conv2d(img1, window, padding=padd, groups=channel)
|
32 |
+
mu2 = F.conv2d(img2, window, padding=padd, groups=channel)
|
33 |
+
|
34 |
+
mu1_sq = mu1.pow(2)
|
35 |
+
mu2_sq = mu2.pow(2)
|
36 |
+
mu1_mu2 = mu1 * mu2
|
37 |
+
|
38 |
+
sigma1_sq = F.conv2d(img1 * img1, window, padding=padd, groups=channel) - mu1_sq
|
39 |
+
sigma2_sq = F.conv2d(img2 * img2, window, padding=padd, groups=channel) - mu2_sq
|
40 |
+
sigma12 = F.conv2d(img1 * img2, window, padding=padd, groups=channel) - mu1_mu2
|
41 |
+
|
42 |
+
C1 = 0.01 ** 2
|
43 |
+
C2 = 0.03 ** 2
|
44 |
+
|
45 |
+
ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
|
46 |
+
|
47 |
+
v1 = 2.0 * sigma12 + C2
|
48 |
+
v2 = sigma1_sq + sigma2_sq + C2
|
49 |
+
cs = torch.mean(v1 / v2)
|
50 |
+
|
51 |
+
if size_average:
|
52 |
+
ret = ssim_map.mean()
|
53 |
+
else:
|
54 |
+
ret = ssim_map.mean(1).mean(1).mean(1)
|
55 |
+
|
56 |
+
if full:
|
57 |
+
return ret, cs
|
58 |
+
return ret
|
59 |
+
|
60 |
+
|
61 |
+
class SSIM(torch.nn.Module):
|
62 |
+
def __init__(self, window_size=11, size_average=True):
|
63 |
+
super(SSIM, self).__init__()
|
64 |
+
self.window_size = window_size
|
65 |
+
self.size_average = size_average
|
66 |
+
self.channel = 1
|
67 |
+
self.window = create_window(window_size, self.channel)
|
68 |
+
|
69 |
+
def forward(self, img1, img2):
|
70 |
+
(_, channel, _, _) = img1.size()
|
71 |
+
|
72 |
+
if channel == self.channel and self.window.data.type() == img1.data.type():
|
73 |
+
window = self.window
|
74 |
+
else:
|
75 |
+
window = create_window(self.window_size, channel)
|
76 |
+
|
77 |
+
if img1.is_cuda:
|
78 |
+
window = window.cuda(img1.get_device())
|
79 |
+
window = window.type_as(img1)
|
80 |
+
|
81 |
+
self.window = window
|
82 |
+
self.channel = channel
|
83 |
+
|
84 |
+
return _ssim(img1, img2, window, self.window_size, channel, self.size_average)
|
85 |
+
|
86 |
+
|
87 |
+
def ssim(img1, img2, window_size=11, size_average=True, full=False):
|
88 |
+
(_, channel, height, width) = img1.size()
|
89 |
+
|
90 |
+
real_size = min(window_size, height, width)
|
91 |
+
window = create_window(real_size, channel)
|
92 |
+
|
93 |
+
if img1.is_cuda:
|
94 |
+
window = window.cuda(img1.get_device())
|
95 |
+
window = window.type_as(img1)
|
96 |
+
|
97 |
+
return _ssim(img1, img2, window, real_size, channel, size_average, full=full)
|
98 |
+
|
99 |
+
|
100 |
+
def msssim(img1, img2, window_size=11, size_average=True):
|
101 |
+
# TODO: fix NAN results
|
102 |
+
if img1.size() != img2.size():
|
103 |
+
raise RuntimeError('Input images must have the same shape (%s vs. %s).' %
|
104 |
+
(img1.size(), img2.size()))
|
105 |
+
if len(img1.size()) != 4:
|
106 |
+
raise RuntimeError('Input images must have four dimensions, not %d' %
|
107 |
+
len(img1.size()))
|
108 |
+
|
109 |
+
weights = torch.tensor([0.0448, 0.2856, 0.3001, 0.2363, 0.1333], dtype=img1.dtype)
|
110 |
+
if img1.is_cuda:
|
111 |
+
weights = weights.cuda(img1.get_device())
|
112 |
+
|
113 |
+
levels = weights.size()[0]
|
114 |
+
mssim = []
|
115 |
+
mcs = []
|
116 |
+
for _ in range(levels):
|
117 |
+
sim, cs = ssim(img1, img2, window_size=window_size, size_average=size_average, full=True)
|
118 |
+
mssim.append(sim)
|
119 |
+
mcs.append(cs)
|
120 |
+
|
121 |
+
img1 = F.avg_pool2d(img1, (2, 2))
|
122 |
+
img2 = F.avg_pool2d(img2, (2, 2))
|
123 |
+
|
124 |
+
mssim = torch.stack(mssim)
|
125 |
+
mcs = torch.stack(mcs)
|
126 |
+
return (torch.prod(mcs[0:levels - 1] ** weights[0:levels - 1]) *
|
127 |
+
(mssim[levels - 1] ** weights[levels - 1]))
|
128 |
+
|
129 |
+
|
130 |
+
class MSSSIM(torch.nn.Module):
|
131 |
+
def __init__(self, window_size=11, size_average=True, channel=3):
|
132 |
+
super(MSSSIM, self).__init__()
|
133 |
+
self.window_size = window_size
|
134 |
+
self.size_average = size_average
|
135 |
+
self.channel = channel
|
136 |
+
|
137 |
+
def forward(self, img1, img2):
|
138 |
+
# TODO: store window between calls if possible
|
139 |
+
return msssim(img1, img2, window_size=self.window_size, size_average=self.size_average)
|
140 |
+
|
141 |
+
|
142 |
+
def calc_psnr(sr, hr, scale=0, benchmark=False):
|
143 |
+
# adapt from EDSR: https://github.com/thstkdgus35/EDSR-PyTorch
|
144 |
+
diff = (sr - hr).data
|
145 |
+
if benchmark:
|
146 |
+
shave = scale
|
147 |
+
if diff.size(1) > 1:
|
148 |
+
convert = diff.new(1, 3, 1, 1)
|
149 |
+
convert[0, 0, 0, 0] = 65.738
|
150 |
+
convert[0, 1, 0, 0] = 129.057
|
151 |
+
convert[0, 2, 0, 0] = 25.064
|
152 |
+
diff.mul_(convert).div_(256)
|
153 |
+
diff = diff.sum(dim=1, keepdim=True)
|
154 |
+
else:
|
155 |
+
shave = scale + 6
|
156 |
+
|
157 |
+
valid = diff[:, :, shave:-shave, shave:-shave]
|
158 |
+
mse = valid.pow(2).mean()
|
159 |
+
|
160 |
+
return -10 * math.log10(mse)
|
161 |
+
|
162 |
+
|
163 |
+
# +++++++++++++++++++++++++++++++++++++
|
164 |
+
# PSNR
|
165 |
+
# -------------------------------------
|
166 |
+
from torch import nn
|
167 |
+
|
168 |
+
|
169 |
+
def psnr(predict, target):
|
170 |
+
with torch.no_grad():
|
171 |
+
criteria = nn.MSELoss()
|
172 |
+
mse = criteria(predict, target)
|
173 |
+
return -10 * torch.log10(mse)
|
Waifu2x/utils/prepare_images.py
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import glob
|
3 |
+
import os
|
4 |
+
from multiprocessing.dummy import Pool as ThreadPool
|
5 |
+
|
6 |
+
from PIL import Image
|
7 |
+
from torchvision.transforms.functional import to_tensor
|
8 |
+
|
9 |
+
from ..Models import *
|
10 |
+
|
11 |
+
|
12 |
+
class ImageSplitter:
|
13 |
+
# key points:
|
14 |
+
# Boarder padding and over-lapping img splitting to avoid the instability of edge value
|
15 |
+
# Thanks Waifu2x's autorh nagadomi for suggestions (https://github.com/nagadomi/waifu2x/issues/238)
|
16 |
+
|
17 |
+
def __init__(self, seg_size=48, scale_factor=2, boarder_pad_size=3):
|
18 |
+
self.seg_size = seg_size
|
19 |
+
self.scale_factor = scale_factor
|
20 |
+
self.pad_size = boarder_pad_size
|
21 |
+
self.height = 0
|
22 |
+
self.width = 0
|
23 |
+
self.upsampler = nn.Upsample(scale_factor=scale_factor, mode='bilinear')
|
24 |
+
|
25 |
+
def split_img_tensor(self, pil_img, scale_method=Image.BILINEAR, img_pad=0):
|
26 |
+
# resize image and convert them into tensor
|
27 |
+
img_tensor = to_tensor(pil_img).unsqueeze(0)
|
28 |
+
img_tensor = nn.ReplicationPad2d(self.pad_size)(img_tensor)
|
29 |
+
batch, channel, height, width = img_tensor.size()
|
30 |
+
self.height = height
|
31 |
+
self.width = width
|
32 |
+
|
33 |
+
if scale_method is not None:
|
34 |
+
img_up = pil_img.resize((2 * pil_img.size[0], 2 * pil_img.size[1]), scale_method)
|
35 |
+
img_up = to_tensor(img_up).unsqueeze(0)
|
36 |
+
img_up = nn.ReplicationPad2d(self.pad_size * self.scale_factor)(img_up)
|
37 |
+
|
38 |
+
patch_box = []
|
39 |
+
# avoid the residual part is smaller than the padded size
|
40 |
+
if height % self.seg_size < self.pad_size or width % self.seg_size < self.pad_size:
|
41 |
+
self.seg_size += self.scale_factor * self.pad_size
|
42 |
+
|
43 |
+
# split image into over-lapping pieces
|
44 |
+
for i in range(self.pad_size, height, self.seg_size):
|
45 |
+
for j in range(self.pad_size, width, self.seg_size):
|
46 |
+
part = img_tensor[:, :,
|
47 |
+
(i - self.pad_size):min(i + self.pad_size + self.seg_size, height),
|
48 |
+
(j - self.pad_size):min(j + self.pad_size + self.seg_size, width)]
|
49 |
+
if img_pad > 0:
|
50 |
+
part = nn.ZeroPad2d(img_pad)(part)
|
51 |
+
if scale_method is not None:
|
52 |
+
# part_up = self.upsampler(part)
|
53 |
+
part_up = img_up[:, :,
|
54 |
+
self.scale_factor * (i - self.pad_size):min(i + self.pad_size + self.seg_size,
|
55 |
+
height) * self.scale_factor,
|
56 |
+
self.scale_factor * (j - self.pad_size):min(j + self.pad_size + self.seg_size,
|
57 |
+
width) * self.scale_factor]
|
58 |
+
|
59 |
+
patch_box.append((part, part_up))
|
60 |
+
else:
|
61 |
+
patch_box.append(part)
|
62 |
+
return patch_box
|
63 |
+
|
64 |
+
def merge_img_tensor(self, list_img_tensor):
|
65 |
+
out = torch.zeros((1, 3, self.height * self.scale_factor, self.width * self.scale_factor))
|
66 |
+
img_tensors = copy.copy(list_img_tensor)
|
67 |
+
rem = self.pad_size * 2
|
68 |
+
|
69 |
+
pad_size = self.scale_factor * self.pad_size
|
70 |
+
seg_size = self.scale_factor * self.seg_size
|
71 |
+
height = self.scale_factor * self.height
|
72 |
+
width = self.scale_factor * self.width
|
73 |
+
for i in range(pad_size, height, seg_size):
|
74 |
+
for j in range(pad_size, width, seg_size):
|
75 |
+
part = img_tensors.pop(0)
|
76 |
+
part = part[:, :, rem:-rem, rem:-rem]
|
77 |
+
# might have error
|
78 |
+
if len(part.size()) > 3:
|
79 |
+
_, _, p_h, p_w = part.size()
|
80 |
+
out[:, :, i:i + p_h, j:j + p_w] = part
|
81 |
+
# out[:,:,
|
82 |
+
# self.scale_factor*i:self.scale_factor*i+p_h,
|
83 |
+
# self.scale_factor*j:self.scale_factor*j+p_w] = part
|
84 |
+
out = out[:, :, rem:-rem, rem:-rem]
|
85 |
+
return out
|
86 |
+
|
87 |
+
|
88 |
+
def load_single_image(img_file,
|
89 |
+
up_scale=False,
|
90 |
+
up_scale_factor=2,
|
91 |
+
up_scale_method=Image.BILINEAR,
|
92 |
+
zero_padding=False):
|
93 |
+
img = Image.open(img_file).convert("RGB")
|
94 |
+
out = to_tensor(img).unsqueeze(0)
|
95 |
+
if zero_padding:
|
96 |
+
out = nn.ZeroPad2d(zero_padding)(out)
|
97 |
+
if up_scale:
|
98 |
+
size = tuple(map(lambda x: x * up_scale_factor, img.size))
|
99 |
+
img_up = img.resize(size, up_scale_method)
|
100 |
+
img_up = to_tensor(img_up).unsqueeze(0)
|
101 |
+
out = (out, img_up)
|
102 |
+
|
103 |
+
return out
|
104 |
+
|
105 |
+
|
106 |
+
def standardize_img_format(img_folder):
|
107 |
+
def process(img_file):
|
108 |
+
img_path = os.path.dirname(img_file)
|
109 |
+
img_name, _ = os.path.basename(img_file).split(".")
|
110 |
+
out = os.path.join(img_path, img_name + ".JPEG")
|
111 |
+
os.rename(img_file, out)
|
112 |
+
|
113 |
+
list_imgs = []
|
114 |
+
for i in ['png', "jpeg", 'jpg']:
|
115 |
+
list_imgs.extend(glob.glob(img_folder + "**/*." + i, recursive=True))
|
116 |
+
print("Found {} images.".format(len(list_imgs)))
|
117 |
+
pool = ThreadPool(4)
|
118 |
+
pool.map(process, list_imgs)
|
119 |
+
pool.close()
|
120 |
+
pool.join()
|
api.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
# file: api.py.py
|
3 |
+
# time: 20:37 2022/12/6
|
4 |
+
# author: yangheng <hy345@exeter.ac.uk>
|
5 |
+
# github: https://github.com/yangheng95
|
6 |
+
# huggingface: https://huggingface.co/yangheng
|
7 |
+
# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en
|
8 |
+
# Copyright (C) 2021. All Rights Reserved.
|
9 |
+
import base64
|
10 |
+
import requests
|
11 |
+
from PIL import Image
|
12 |
+
from io import BytesIO
|
13 |
+
|
14 |
+
import requests
|
15 |
+
|
16 |
+
url = "https://images.pexels.com/photos/666839/pexels-photo-666839.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"
|
17 |
+
|
18 |
+
response = requests.get(url)
|
19 |
+
image = Image.open(BytesIO(response.content))
|
20 |
+
# convert image to base64 string
|
21 |
+
image = base64.b64encode(image.tobytes()).decode('utf-8')
|
22 |
+
|
23 |
+
response = requests.post("http://127.0.0.1:7860/run/magnify_image", json={
|
24 |
+
"data": [
|
25 |
+
"data:image/png;base64,{}".format(image),
|
26 |
+
2,
|
27 |
+
]}).json()
|
28 |
+
|
29 |
+
data = response["data"]
|
30 |
+
|
31 |
+
img = Image.open(BytesIO(response.content))
|
32 |
+
img.show()
|
33 |
+
img.save('test_api.png')
|
app.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import random
|
3 |
+
from io import BytesIO
|
4 |
+
|
5 |
+
import autocuda
|
6 |
+
import requests
|
7 |
+
from pyabsa.utils.pyabsa_utils import fprint
|
8 |
+
|
9 |
+
import gradio as gr
|
10 |
+
import torch
|
11 |
+
from PIL import Image
|
12 |
+
import datetime
|
13 |
+
import time
|
14 |
+
from Waifu2x.magnify import ImageMagnifier
|
15 |
+
|
16 |
+
magnifier = ImageMagnifier()
|
17 |
+
|
18 |
+
start_time = time.time()
|
19 |
+
|
20 |
+
CUDA_VISIBLE_DEVICES = ''
|
21 |
+
device = autocuda.auto_cuda()
|
22 |
+
|
23 |
+
dtype = torch.float16 if device != 'cpu' else torch.float32
|
24 |
+
|
25 |
+
def magnify_image(image, scale_factor=2):
|
26 |
+
start_time = time.time()
|
27 |
+
image = magnifier.magnify(image, scale_factor=scale_factor)
|
28 |
+
fprint(f'Inference time: {time.time() - start_time:.2f}s')
|
29 |
+
return image
|
30 |
+
|
31 |
+
with gr.Blocks() as demo:
|
32 |
+
if not os.path.exists('imgs'):
|
33 |
+
os.mkdir('imgs')
|
34 |
+
|
35 |
+
gr.Markdown('# Free Image Scale Up Demo')
|
36 |
+
gr.Markdown('## 免费图片分辨率放大演示')
|
37 |
+
gr.Markdown('## Powered by Waifu2x')
|
38 |
+
gr.Markdown("## Author: [yangheng95](https://github.com/yangheng95) Github:[Github](https://github.com/yangheng95/SuperResolutionAnimeDiffusion)")
|
39 |
+
|
40 |
+
with gr.Row():
|
41 |
+
with gr.Column(scale=40):
|
42 |
+
with gr.Group():
|
43 |
+
image_in = gr.Image(label="Image", height=512, tool="editor", type="pil")
|
44 |
+
|
45 |
+
with gr.Row():
|
46 |
+
scale_factor = gr.Slider(1, 8, label='Scale factor (to magnify image) (1, 2, 4, 8)',
|
47 |
+
value=2,
|
48 |
+
step=1)
|
49 |
+
with gr.Row():
|
50 |
+
generate = gr.Button(value="Magnify", label="Magnify")
|
51 |
+
|
52 |
+
error_output = gr.Markdown()
|
53 |
+
|
54 |
+
with gr.Column(scale=60):
|
55 |
+
gr.Markdown('## Click the right button to save the magnified image')
|
56 |
+
gr.Markdown('## 右键点击图片保存放大后的图片')
|
57 |
+
with gr.Group():
|
58 |
+
image_out = gr.Image(height=512)
|
59 |
+
inputs = [image_in, scale_factor]
|
60 |
+
outputs = [image_out]
|
61 |
+
generate.click(magnify_image, inputs=inputs, outputs=outputs, api_name="magnify_image")
|
62 |
+
|
63 |
+
print(f"Space built in {time.time() - start_time:.2f} seconds")
|
64 |
+
|
65 |
+
demo.launch(enable_queue=True, share=False)
|