p1atdev commited on
Commit
f561c25
1 Parent(s): d02110f

chore: use transformers version

Browse files
README.md CHANGED
@@ -4,7 +4,7 @@ emoji: 💭
4
  colorFrom: green
5
  colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 3.28.2
8
  app_file: app.py
9
  pinned: false
10
  license: mit
 
4
  colorFrom: green
5
  colorTo: yellow
6
  sdk: gradio
7
+ sdk_version: 4.21.0
8
  app_file: app.py
9
  pinned: false
10
  license: mit
app.py CHANGED
@@ -3,13 +3,31 @@ from setup import setup
3
  import torch
4
  import gc
5
  from PIL import Image
6
- from manga_line_extraction.model import MangaLineExtractor
7
  from anime2sketch.model import Anime2Sketch
 
8
 
9
  setup()
10
 
11
  print("Setup finished")
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  def flush():
15
  gc.collect()
@@ -18,19 +36,13 @@ def flush():
18
 
19
  @torch.no_grad()
20
  def extract(image):
21
- extractor = MangaLineExtractor("./models/erika.pth", "cpu")
22
- result = extractor.predict(image)
23
- del extractor
24
- flush()
25
  return result
26
 
27
 
28
  @torch.no_grad()
29
  def convert_to_sketch(image):
30
- to_sketch = Anime2Sketch("./models/netG.pth", "cpu")
31
- result = to_sketch.predict(image)
32
- del to_sketch
33
- flush()
34
  return result
35
 
36
 
@@ -51,6 +63,9 @@ def ui():
51
  Original repos:
52
  - [MangaLineExtraction_PyTorch](https://github.com/ljsabc/MangaLineExtraction_PyTorch)
53
  - [Anime2Sketch](https://github.com/Mukosame/Anime2Sketch)
 
 
 
54
  """
55
  )
56
 
@@ -71,14 +86,9 @@ def ui():
71
  gr.Examples(
72
  fn=start,
73
  examples=[
 
74
  ["./examples/1.jpg"],
75
  ["./examples/2.jpg"],
76
- ["./examples/3.jpg"],
77
- ["./examples/4.jpg"],
78
- ["./examples/5.jpg"],
79
- ["./examples/6.jpg"],
80
- ["./examples/7.jpg"],
81
- ["./examples/8.jpg"],
82
  ],
83
  inputs=[input_img],
84
  outputs=[extract_output_img, to_sketch_output_img],
 
3
  import torch
4
  import gc
5
  from PIL import Image
6
+ from transformers import AutoModel, AutoImageProcessor
7
  from anime2sketch.model import Anime2Sketch
8
+ # import spaces
9
 
10
  setup()
11
 
12
  print("Setup finished")
13
 
14
+ MLE_MODEL_REPO = "p1atdev/MangaLineExtraction-hf"
15
+
16
+ class MangaLineExtractor:
17
+ model = AutoModel.from_pretrained(MLE_MODEL_REPO, trust_remote_code=True)
18
+ processor = AutoImageProcessor.from_pretrained(MLE_MODEL_REPO, trust_remote_code=True)
19
+
20
+ # @spaces.GPU
21
+ @torch.no_grad()
22
+ def __call__(self, image: Image.Image) -> Image.Image:
23
+ inputs = self.processor(image, return_tensors="pt")
24
+ outputs = self.model(inputs.pixel_values)
25
+
26
+ line_image = Image.fromarray(outputs.pixel_values[0].numpy().astype("uint8"), mode="L")
27
+ return line_image
28
+
29
+ mle_model = MangaLineExtractor()
30
+ a2s_model = Anime2Sketch("./models/netG.pth", "cpu")
31
 
32
  def flush():
33
  gc.collect()
 
36
 
37
  @torch.no_grad()
38
  def extract(image):
39
+ result = mle_model(image)
 
 
 
40
  return result
41
 
42
 
43
  @torch.no_grad()
44
  def convert_to_sketch(image):
45
+ result = a2s_model.predict(image)
 
 
 
46
  return result
47
 
48
 
 
63
  Original repos:
64
  - [MangaLineExtraction_PyTorch](https://github.com/ljsabc/MangaLineExtraction_PyTorch)
65
  - [Anime2Sketch](https://github.com/Mukosame/Anime2Sketch)
66
+
67
+ Using with 🤗 transformers:
68
+ - [MangaLineExtraction-hf](https://huggingface.co/p1atdev/MangaLineExtraction-hf)
69
  """
70
  )
71
 
 
86
  gr.Examples(
87
  fn=start,
88
  examples=[
89
+ ["./examples/0.jpg"],
90
  ["./examples/1.jpg"],
91
  ["./examples/2.jpg"],
 
 
 
 
 
 
92
  ],
93
  inputs=[input_img],
94
  outputs=[extract_output_img, to_sketch_output_img],
examples/0.jpg ADDED
examples/1.jpg CHANGED
examples/2.jpg CHANGED
examples/3.jpg DELETED
Binary file (77 kB)
 
examples/4.jpg DELETED
Binary file (184 kB)
 
examples/5.jpg DELETED
Binary file (113 kB)
 
examples/6.jpg DELETED
Binary file (105 kB)
 
examples/7.jpg DELETED
Binary file (100 kB)
 
examples/8.jpg DELETED
Binary file (90.7 kB)
 
manga_line_extraction/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2021 Miaomiao Li
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
manga_line_extraction/model.py DELETED
@@ -1,323 +0,0 @@
1
- import os
2
- import torch
3
- import torch.nn as nn
4
- from torch.utils.data.dataset import Dataset
5
- from PIL import Image
6
- import fnmatch
7
- import cv2
8
-
9
- import sys
10
-
11
- import numpy as np
12
-
13
- # torch.set_printoptions(precision=10)
14
-
15
-
16
- class _bn_relu_conv(nn.Module):
17
- def __init__(self, in_filters, nb_filters, fw, fh, subsample=1):
18
- super(_bn_relu_conv, self).__init__()
19
- self.model = nn.Sequential(
20
- nn.BatchNorm2d(in_filters, eps=1e-3),
21
- nn.LeakyReLU(0.2),
22
- nn.Conv2d(
23
- in_filters,
24
- nb_filters,
25
- (fw, fh),
26
- stride=subsample,
27
- padding=(fw // 2, fh // 2),
28
- padding_mode="zeros",
29
- ),
30
- )
31
-
32
- def forward(self, x):
33
- return self.model(x)
34
-
35
- # the following are for debugs
36
- print(
37
- "****",
38
- np.max(x.cpu().numpy()),
39
- np.min(x.cpu().numpy()),
40
- np.mean(x.cpu().numpy()),
41
- np.std(x.cpu().numpy()),
42
- x.shape,
43
- )
44
- for i, layer in enumerate(self.model):
45
- if i != 2:
46
- x = layer(x)
47
- else:
48
- x = layer(x)
49
- # x = nn.functional.pad(x, (1, 1, 1, 1), mode='constant', value=0)
50
- print(
51
- "____",
52
- np.max(x.cpu().numpy()),
53
- np.min(x.cpu().numpy()),
54
- np.mean(x.cpu().numpy()),
55
- np.std(x.cpu().numpy()),
56
- x.shape,
57
- )
58
- print(x[0])
59
- return x
60
-
61
-
62
- class _u_bn_relu_conv(nn.Module):
63
- def __init__(self, in_filters, nb_filters, fw, fh, subsample=1):
64
- super(_u_bn_relu_conv, self).__init__()
65
- self.model = nn.Sequential(
66
- nn.BatchNorm2d(in_filters, eps=1e-3),
67
- nn.LeakyReLU(0.2),
68
- nn.Conv2d(
69
- in_filters,
70
- nb_filters,
71
- (fw, fh),
72
- stride=subsample,
73
- padding=(fw // 2, fh // 2),
74
- ),
75
- nn.Upsample(scale_factor=2, mode="nearest"),
76
- )
77
-
78
- def forward(self, x):
79
- return self.model(x)
80
-
81
-
82
- class _shortcut(nn.Module):
83
- def __init__(self, in_filters, nb_filters, subsample=1):
84
- super(_shortcut, self).__init__()
85
- self.process = False
86
- self.model = None
87
- if in_filters != nb_filters or subsample != 1:
88
- self.process = True
89
- self.model = nn.Sequential(
90
- nn.Conv2d(in_filters, nb_filters, (1, 1), stride=subsample)
91
- )
92
-
93
- def forward(self, x, y):
94
- # print(x.size(), y.size(), self.process)
95
- if self.process:
96
- y0 = self.model(x)
97
- # print("merge+", torch.max(y0+y), torch.min(y0+y),torch.mean(y0+y), torch.std(y0+y), y0.shape)
98
- return y0 + y
99
- else:
100
- # print("merge", torch.max(x+y), torch.min(x+y),torch.mean(x+y), torch.std(x+y), y.shape)
101
- return x + y
102
-
103
-
104
- class _u_shortcut(nn.Module):
105
- def __init__(self, in_filters, nb_filters, subsample):
106
- super(_u_shortcut, self).__init__()
107
- self.process = False
108
- self.model = None
109
- if in_filters != nb_filters:
110
- self.process = True
111
- self.model = nn.Sequential(
112
- nn.Conv2d(
113
- in_filters,
114
- nb_filters,
115
- (1, 1),
116
- stride=subsample,
117
- padding_mode="zeros",
118
- ),
119
- nn.Upsample(scale_factor=2, mode="nearest"),
120
- )
121
-
122
- def forward(self, x, y):
123
- if self.process:
124
- return self.model(x) + y
125
- else:
126
- return x + y
127
-
128
-
129
- class basic_block(nn.Module):
130
- def __init__(self, in_filters, nb_filters, init_subsample=1):
131
- super(basic_block, self).__init__()
132
- self.conv1 = _bn_relu_conv(
133
- in_filters, nb_filters, 3, 3, subsample=init_subsample
134
- )
135
- self.residual = _bn_relu_conv(nb_filters, nb_filters, 3, 3)
136
- self.shortcut = _shortcut(in_filters, nb_filters, subsample=init_subsample)
137
-
138
- def forward(self, x):
139
- x1 = self.conv1(x)
140
- x2 = self.residual(x1)
141
- return self.shortcut(x, x2)
142
-
143
-
144
- class _u_basic_block(nn.Module):
145
- def __init__(self, in_filters, nb_filters, init_subsample=1):
146
- super(_u_basic_block, self).__init__()
147
- self.conv1 = _u_bn_relu_conv(
148
- in_filters, nb_filters, 3, 3, subsample=init_subsample
149
- )
150
- self.residual = _bn_relu_conv(nb_filters, nb_filters, 3, 3)
151
- self.shortcut = _u_shortcut(in_filters, nb_filters, subsample=init_subsample)
152
-
153
- def forward(self, x):
154
- y = self.residual(self.conv1(x))
155
- return self.shortcut(x, y)
156
-
157
-
158
- class _residual_block(nn.Module):
159
- def __init__(self, in_filters, nb_filters, repetitions, is_first_layer=False):
160
- super(_residual_block, self).__init__()
161
- layers = []
162
- for i in range(repetitions):
163
- init_subsample = 1
164
- if i == repetitions - 1 and not is_first_layer:
165
- init_subsample = 2
166
- if i == 0:
167
- l = basic_block(
168
- in_filters=in_filters,
169
- nb_filters=nb_filters,
170
- init_subsample=init_subsample,
171
- )
172
- else:
173
- l = basic_block(
174
- in_filters=nb_filters,
175
- nb_filters=nb_filters,
176
- init_subsample=init_subsample,
177
- )
178
- layers.append(l)
179
-
180
- self.model = nn.Sequential(*layers)
181
-
182
- def forward(self, x):
183
- return self.model(x)
184
-
185
-
186
- class _upsampling_residual_block(nn.Module):
187
- def __init__(self, in_filters, nb_filters, repetitions):
188
- super(_upsampling_residual_block, self).__init__()
189
- layers = []
190
- for i in range(repetitions):
191
- l = None
192
- if i == 0:
193
- l = _u_basic_block(
194
- in_filters=in_filters, nb_filters=nb_filters
195
- ) # (input)
196
- else:
197
- l = basic_block(in_filters=nb_filters, nb_filters=nb_filters) # (input)
198
- layers.append(l)
199
-
200
- self.model = nn.Sequential(*layers)
201
-
202
- def forward(self, x):
203
- return self.model(x)
204
-
205
-
206
- class res_skip(nn.Module):
207
- def __init__(self):
208
- super(res_skip, self).__init__()
209
- self.block0 = _residual_block(
210
- in_filters=1, nb_filters=24, repetitions=2, is_first_layer=True
211
- ) # (input)
212
- self.block1 = _residual_block(
213
- in_filters=24, nb_filters=48, repetitions=3
214
- ) # (block0)
215
- self.block2 = _residual_block(
216
- in_filters=48, nb_filters=96, repetitions=5
217
- ) # (block1)
218
- self.block3 = _residual_block(
219
- in_filters=96, nb_filters=192, repetitions=7
220
- ) # (block2)
221
- self.block4 = _residual_block(
222
- in_filters=192, nb_filters=384, repetitions=12
223
- ) # (block3)
224
-
225
- self.block5 = _upsampling_residual_block(
226
- in_filters=384, nb_filters=192, repetitions=7
227
- ) # (block4)
228
- self.res1 = _shortcut(
229
- in_filters=192, nb_filters=192
230
- ) # (block3, block5, subsample=(1,1))
231
-
232
- self.block6 = _upsampling_residual_block(
233
- in_filters=192, nb_filters=96, repetitions=5
234
- ) # (res1)
235
- self.res2 = _shortcut(
236
- in_filters=96, nb_filters=96
237
- ) # (block2, block6, subsample=(1,1))
238
-
239
- self.block7 = _upsampling_residual_block(
240
- in_filters=96, nb_filters=48, repetitions=3
241
- ) # (res2)
242
- self.res3 = _shortcut(
243
- in_filters=48, nb_filters=48
244
- ) # (block1, block7, subsample=(1,1))
245
-
246
- self.block8 = _upsampling_residual_block(
247
- in_filters=48, nb_filters=24, repetitions=2
248
- ) # (res3)
249
- self.res4 = _shortcut(
250
- in_filters=24, nb_filters=24
251
- ) # (block0,block8, subsample=(1,1))
252
-
253
- self.block9 = _residual_block(
254
- in_filters=24, nb_filters=16, repetitions=2, is_first_layer=True
255
- ) # (res4)
256
- self.conv15 = _bn_relu_conv(
257
- in_filters=16, nb_filters=1, fh=1, fw=1, subsample=1
258
- ) # (block7)
259
-
260
- def forward(self, x):
261
- x0 = self.block0(x)
262
- x1 = self.block1(x0)
263
- x2 = self.block2(x1)
264
- x3 = self.block3(x2)
265
- x4 = self.block4(x3)
266
-
267
- x5 = self.block5(x4)
268
- res1 = self.res1(x3, x5)
269
-
270
- x6 = self.block6(res1)
271
- res2 = self.res2(x2, x6)
272
-
273
- x7 = self.block7(res2)
274
- res3 = self.res3(x1, x7)
275
-
276
- x8 = self.block8(res3)
277
- res4 = self.res4(x0, x8)
278
-
279
- x9 = self.block9(res4)
280
- y = self.conv15(x9)
281
-
282
- return y
283
-
284
-
285
- class MangaLineExtractor:
286
- def __init__(self, model_path: str = "erika.pth", device: str = "cpu"):
287
- self.model = res_skip()
288
- self.model.load_state_dict(torch.load(model_path))
289
-
290
- self.is_cuda = torch.cuda.is_available() and device == "cuda"
291
- if self.is_cuda:
292
- self.model.cuda()
293
- else:
294
- self.model.cpu()
295
-
296
- self.model.eval()
297
-
298
- def predict(self, image):
299
- src = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
300
-
301
- rows = int(np.ceil(src.shape[0] / 16)) * 16
302
- cols = int(np.ceil(src.shape[1] / 16)) * 16
303
-
304
- # manually construct a batch. You can change it based on your usecases.
305
- patch = np.ones((1, 1, rows, cols), dtype=np.float32)
306
- patch[0, 0, 0 : src.shape[0], 0 : src.shape[1]] = src
307
-
308
- if self.is_cuda:
309
- tensor = torch.from_numpy(patch).cuda()
310
- else:
311
- tensor = torch.from_numpy(patch).cpu()
312
-
313
- y = self.model(tensor)
314
-
315
- yc = y.detach().numpy()[0, 0, :, :]
316
- yc[yc > 255] = 255
317
- yc[yc < 0] = 0
318
- yc = yc / 255.0
319
-
320
- output = yc[0 : src.shape[0], 0 : src.shape[1]]
321
- output = cv2.cvtColor(output, cv2.COLOR_GRAY2BGR)
322
-
323
- return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -2,4 +2,7 @@ torch
2
  torchvision
3
  numpy
4
  opencv-python
5
- huggingface_hub
 
 
 
 
2
  torchvision
3
  numpy
4
  opencv-python
5
+ huggingface_hub
6
+ spaces
7
+ safetensors
8
+ transformers
setup.py CHANGED
@@ -5,21 +5,8 @@ from utils import custom_drive_cache_dir, get_drive
5
 
6
  HF_TOKEN = os.getenv("HF_TOKEN")
7
 
8
- MANGA_LINE_EXTRACTION_MODEL = "https://github.com/ljsabc/MangaLineExtraction_PyTorch/releases/download/v1/erika.pth"
9
  ANIME2SKETCH_MODEL = {"REPO_ID": "p1atdev/Anime2Sketch", "FILENAME": "netG.pth"}
10
 
11
-
12
- def download_manga_line_extraction_model():
13
- if os.path.exists("./models/erika.pth"):
14
- return
15
-
16
- with requests.get(MANGA_LINE_EXTRACTION_MODEL, stream=True) as r:
17
- r.raise_for_status()
18
- with open("./models/erika.pth", "wb") as f:
19
- for chunk in r.iter_content(chunk_size=8192):
20
- f.write(chunk)
21
-
22
-
23
  def download_anime2sketch_model():
24
  if os.path.exists("./models/netG.pth"):
25
  return
@@ -39,5 +26,4 @@ def download_anime2sketch_model():
39
  def setup():
40
  if not os.path.exists("./models"):
41
  os.makedirs("./models")
42
- download_manga_line_extraction_model()
43
  download_anime2sketch_model()
 
5
 
6
  HF_TOKEN = os.getenv("HF_TOKEN")
7
 
 
8
  ANIME2SKETCH_MODEL = {"REPO_ID": "p1atdev/Anime2Sketch", "FILENAME": "netG.pth"}
9
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  def download_anime2sketch_model():
11
  if os.path.exists("./models/netG.pth"):
12
  return
 
26
  def setup():
27
  if not os.path.exists("./models"):
28
  os.makedirs("./models")
 
29
  download_anime2sketch_model()