chenyingxu commited on
Commit
3d76444
Β·
verified Β·
1 Parent(s): a7a571c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -30
app.py CHANGED
@@ -5,45 +5,141 @@ import gradio as gr
5
  import cv2
6
  import os
7
  from PIL import Image
 
8
 
9
- # ζ¨‘εž‹εŠ θ½½
10
- model1 = torch.load('model.pth', map_location='cpu').eval()
11
- model2 = torch.load('model2.pth', map_location='cpu').eval()
12
 
13
- # ηΌ“ε­˜ε’Œε›Ύεƒε€„η†
14
- cache = {}
 
 
15
 
16
- def preprocess_image(input_img):
17
- img = cv2.imread(input_img)[:, :, ::-1]
18
- img = cv2.resize(img, (256, 256), interpolation=cv2.INTER_CUBIC)
19
- img = np.transpose((img.astype(np.float32) / 255.0 - 0.5) / 0.5, (2, 0, 1))
20
- return torch.tensor(img).unsqueeze(0)
 
 
 
21
 
22
- def postprocess_image(output_tensor, original_size):
23
- output_img = output_tensor.squeeze(0).clamp(0, 1).cpu().numpy()
24
- output_img = np.transpose(output_img, (1, 2, 0))
25
- output_img = (output_img * 255).astype(np.uint8)
26
- return Image.fromarray(cv2.resize(output_img, original_size, interpolation=cv2.INTER_CUBIC))
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  def predict(input_img, ver):
29
- if (input_img, ver) in cache:
30
- return cache[(input_img, ver)]
 
31
 
32
- original_img = cv2.imread(input_img)
33
- original_size = (original_img.shape[1], original_img.shape[0])
34
- input_tensor = preprocess_image(input_img)
 
 
 
35
 
 
 
 
 
 
36
  with torch.no_grad():
37
- output_tensor = model2(input_tensor) if ver == 'Simple Lines' else model1(input_tensor)
 
 
 
 
 
 
 
 
 
38
 
39
- output_img = postprocess_image(output_tensor, original_size)
40
- cache[(input_img, ver)] = output_img
41
  return output_img
42
 
43
- # Gradio η•Œι’
44
- examples = [[os.path.join('.', file), 'Simple Lines'] for file in os.listdir('.')
45
- if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))]
 
 
 
 
 
 
 
46
 
 
47
  iface = gr.Interface(
48
  fn=predict,
49
  inputs=[
@@ -51,10 +147,8 @@ iface = gr.Interface(
51
  gr.Radio(['Complex Lines', 'Simple Lines'], label='version', value='Simple Lines')
52
  ],
53
  outputs=gr.Image(type="pil"),
54
- title="πŸ–ŒοΈ Image to Simple and Complex Artistic Drawings",
55
- examples=examples,
56
- allow_flagging="never",
57
- live=False
58
  )
59
 
60
  iface.launch()
 
5
  import cv2
6
  import os
7
  from PIL import Image
8
+ import torchvision.transforms as transforms
9
 
10
+ # 🧠 Neural network layers
11
+ norm_layer = nn.InstanceNorm2d
 
12
 
13
+ # 🧱 Building block for the generator
14
+ class ResidualBlock(nn.Module):
15
+ def __init__(self, in_features):
16
+ super(ResidualBlock, self).__init__()
17
 
18
+ conv_block = [ nn.ReflectionPad2d(1),
19
+ nn.Conv2d(in_features, in_features, 3),
20
+ norm_layer(in_features),
21
+ nn.ReLU(inplace=True),
22
+ nn.ReflectionPad2d(1),
23
+ nn.Conv2d(in_features, in_features, 3),
24
+ norm_layer(in_features)
25
+ ]
26
 
27
+ self.conv_block = nn.Sequential(*conv_block)
 
 
 
 
28
 
29
+ def forward(self, x):
30
+ return x + self.conv_block(x)
31
+
32
+ # 🎨 Generator model for creating line drawings
33
+ class Generator(nn.Module):
34
+ def __init__(self, input_nc, output_nc, n_residual_blocks=9, sigmoid=True):
35
+ super(Generator, self).__init__()
36
+
37
+ # 🏁 Initial convolution block
38
+ model0 = [ nn.ReflectionPad2d(3),
39
+ nn.Conv2d(input_nc, 64, 7),
40
+ norm_layer(64),
41
+ nn.ReLU(inplace=True) ]
42
+ self.model0 = nn.Sequential(*model0)
43
+
44
+ # πŸ”½ Downsampling
45
+ model1 = []
46
+ in_features = 64
47
+ out_features = in_features*2
48
+ for _ in range(2):
49
+ model1 += [ nn.Conv2d(in_features, out_features, 3, stride=2, padding=1),
50
+ norm_layer(out_features),
51
+ nn.ReLU(inplace=True) ]
52
+ in_features = out_features
53
+ out_features = in_features*2
54
+ self.model1 = nn.Sequential(*model1)
55
+
56
+ # πŸ” Residual blocks
57
+ model2 = []
58
+ for _ in range(n_residual_blocks):
59
+ model2 += [ResidualBlock(in_features)]
60
+ self.model2 = nn.Sequential(*model2)
61
+
62
+ # πŸ”Ό Upsampling
63
+ model3 = []
64
+ out_features = in_features//2
65
+ for _ in range(2):
66
+ model3 += [ nn.ConvTranspose2d(in_features, out_features, 3, stride=2, padding=1, output_padding=1),
67
+ norm_layer(out_features),
68
+ nn.ReLU(inplace=True) ]
69
+ in_features = out_features
70
+ out_features = in_features//2
71
+ self.model3 = nn.Sequential(*model3)
72
+
73
+ # 🎭 Output layer
74
+ model4 = [ nn.ReflectionPad2d(3),
75
+ nn.Conv2d(64, output_nc, 7)]
76
+ if sigmoid:
77
+ model4 += [nn.Sigmoid()]
78
+
79
+ self.model4 = nn.Sequential(*model4)
80
+
81
+ def forward(self, x, cond=None):
82
+ out = self.model0(x)
83
+ out = self.model1(out)
84
+ out = self.model2(out)
85
+ out = self.model3(out)
86
+ out = self.model4(out)
87
+
88
+ return out
89
+
90
+ # πŸ”§ Load the models
91
+ model1 = Generator(3, 1, 3) # Initialize the model architecture
92
+ model1.load_state_dict(torch.load('model.pth', map_location=torch.device('cpu')))
93
+ model1.eval() # Set the model to evaluation mode
94
+
95
+ model2 = Generator(3, 1, 3) # Initialize the model architecture
96
+ model2.load_state_dict(torch.load('model2.pth', map_location=torch.device('cpu')))
97
+ model2.eval() # Set the model to evaluation mode
98
+
99
+ # πŸ–ΌοΈ Function to process the image and create line drawing
100
  def predict(input_img, ver):
101
+ # Open the image and get its original size
102
+ original_img = Image.open(input_img)
103
+ original_size = original_img.size
104
 
105
+ # Define the transformation pipeline
106
+ transform = transforms.Compose([
107
+ transforms.Resize(256, Image.BICUBIC),
108
+ transforms.ToTensor(),
109
+ transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
110
+ ])
111
 
112
+ # Apply the transformation
113
+ input_tensor = transform(original_img)
114
+ input_tensor = input_tensor.unsqueeze(0)
115
+
116
+ # Process the image through the model
117
  with torch.no_grad():
118
+ if ver == 'Simple Lines':
119
+ output = model2(input_tensor)
120
+ else:
121
+ output = model1(input_tensor)
122
+
123
+ # Convert the output tensor to an image
124
+ output_img = transforms.ToPILImage()(output.squeeze().cpu().clamp(0, 1))
125
+
126
+ # Resize the output image back to the original size
127
+ output_img = output_img.resize(original_size, Image.BICUBIC)
128
 
 
 
129
  return output_img
130
 
131
+ # πŸ“ Title for the Gradio interface
132
+ title="πŸ–ŒοΈ Image to Simple and Complex Artistic Drawings"
133
+
134
+ # πŸ–ΌοΈ Dynamically generate examples from images in the directory
135
+ examples = []
136
+ image_dir = '.' # Assuming images are in the current directory
137
+ for file in os.listdir(image_dir):
138
+ if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
139
+ examples.append([file, 'Simple Lines'])
140
+ examples.append([file, 'Complex Lines'])
141
 
142
+ # πŸš€ Create and launch the Gradio interface
143
  iface = gr.Interface(
144
  fn=predict,
145
  inputs=[
 
147
  gr.Radio(['Complex Lines', 'Simple Lines'], label='version', value='Simple Lines')
148
  ],
149
  outputs=gr.Image(type="pil"),
150
+ title=title,
151
+ examples=examples
 
 
152
  )
153
 
154
  iface.launch()