Spaces:
Build error
Build error
Update app.py
Browse files4 unmodified lines56789101112131415161718192021222324252627282930313233343536373839404142434445464748491 unmodified line515253545556575859604 unmodified linesimport cv2import osfrom PIL import Image# 樑εε θ½½model1 = torch.load('model.pth', map_location='cpu').eval()model2 = torch.load('model2.pth', map_location='cpu').eval()# ηΌεεεΎεε€ηcache = {}def preprocess_image(input_img):img = cv2.imread(input_img)[:, :, ::-1]img = cv2.resize(img, (256, 256), interpolation=cv2.INTER_CUBIC)img = np.transpose((img.astype(np.float32) / 255.0 - 0.5) / 0.5, (2, 0, 1))return torch.tensor(img).unsqueeze(0)def postprocess_image(output_tensor, original_size):output_img = output_tensor.squeeze(0).clamp(0, 1).cpu().numpy()output_img = np.transpose(output_img, (1, 2, 0))output_img = (output_img * 255).astype(np.uint8)return Image.fromarray(cv2.resize(output_img, original_size, interpolation=cv2.INTER_CUBIC))def predict(input_img, ver):if (input_img, ver) in cache:return cache[(input_img, ver)]original_img = cv2.imread(input_img)original_size = (original_img.shape[1], original_img.shape[0])input_tensor = preprocess_image(input_img)with torch.no_grad():output_tensor = model2(input_tensor) if ver == 'Simple Lines' else model1(input_tensor)output_img = postprocess_image(output_tensor, original_size)cache[(input_img, ver)] = output_imgreturn output_img# Gradio ηι’examples = [[os.path.join('.', file), 'Simple Lines'] for file in os.listdir('.')if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))]iface = gr.Interface(fn=predict,inputs=[1 unmodified linegr.Radio(['Complex Lines', 'Simple Lines'], label='version', value='Simple Lines')],outputs=gr.Image(type="pil"),title="ποΈ Image to Simple and Complex Artistic Drawings",examples=examples,allow_flagging="never",live=False)iface.launch()4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451 unmodified line1471481491501511521531544 unmodified linesimport cv2import osfrom PIL import Imageimport torchvision.transforms as transforms# π§ Neural network layersnorm_layer = nn.InstanceNorm2d# π§± Building block for the generatorclass ResidualBlock(nn.Module):def __init__(self, in_features):super(ResidualBlock, self).__init__()conv_block = [ nn.ReflectionPad2d(1),nn.Conv2d(in_features, in_features, 3),norm_layer(in_features),nn.ReLU(inplace=True),nn.ReflectionPad2d(1),nn.Conv2d(in_features, in_features, 3),norm_layer(in_features)]self.conv_block = nn.Sequential(*conv_block)def forward(self, x):return x + self.conv_block(x)# π¨ Generator model for creating line drawingsclass Generator(nn.Module):def __init__(self, input_nc, output_nc, n_residual_blocks=9, sigmoid=True):super(Generator, self).__init__()# π Initial convolution blockmodel0 = [ nn.ReflectionPad2d(3),nn.Conv2d(input_nc, 64, 7),norm_layer(64),nn.ReLU(inplace=True) ]self.model0 = nn.Sequential(*model0)# π½ Downsamplingmodel1 = []in_features = 64out_features = in_features*2for _ in range(2):model1 += [ nn.Conv2d(in_features, out_features, 3, stride=2, padding=1),norm_layer(out_features),nn.ReLU(inplace=True) ]in_features = out_featuresout_features = in_features*2self.model1 = nn.Sequential(*model1)# π Residual blocksmodel2 = []for _ in range(n_residual_blocks):model2 += [ResidualBlock(in_features)]self.model2 = nn.Sequential(*model2)# πΌ Upsamplingmodel3 = []out_features = in_features//2for _ in range(2):model3 += [ nn.ConvTranspose2d(in_features, out_features, 3, stride=2, padding=1, output_padding=1),norm_layer(out_features),nn.ReLU(inplace=True) ]in_features = out_featuresout_features = in_features//2self.model3 = nn.Sequential(*model3)# π Output layermodel4 = [ nn.ReflectionPad2d(3),nn.Conv2d(64, output_nc, 7)]if sigmoid:model4 += [nn.Sigmoid()]self.model4 = nn.Sequential(*model4)def forward(self, x, cond=None):out = self.model0(x)out = self.model1(out)out = self.model2(out)out = self.model3(out)out = self.model4(out)return out# π§ Load the modelsmodel1 = Generator(3, 1, 3) # Initialize the model architecturemodel1.load_state_dict(torch.load('model.pth', map_location=torch.device('cpu')))model1.eval() # Set the model to evaluation modemodel2 = Generator(3, 1, 3) # Initialize the model architecturemodel2.load_state_dict(torch.load('model2.pth', map_location=torch.device('cpu')))model2.eval() # Set the model to evaluation mode# πΌοΈ Function to process the image and create line drawingdef predict(input_img, ver):# Open the image and get its original sizeoriginal_img = Image.open(input_img)original_size = original_img.size# Define the transformation pipelinetransform = transforms.Compose([transforms.Resize(256, Image.BICUBIC),transforms.ToTensor(),transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])# Apply the transformationinput_tensor = transform(original_img)input_tensor = input_tensor.unsqueeze(0)# Process the image through the modelwith torch.no_grad():if ver == 'Simple Lines':output = model2(input_tensor)else:output = model1(input_tensor)# Convert the output tensor to an imageoutput_img = transforms.ToPILImage()(output.squeeze().cpu().clamp(0, 1))# Resize the output image back to the original sizeoutput_img = output_img.resize(original_size, Image.BICUBIC)return output_img# π Title for the Gradio interfacetitle="ποΈ Image to Simple and Complex Artistic Drawings"# πΌοΈ Dynamically generate examples from images in the directoryexamples = []image_dir = '.' # Assuming images are in the current directoryfor file in os.listdir(image_dir):if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):examples.append([file, 'Simple Lines'])examples.append([file, 'Complex Lines'])# π Create and launch the Gradio interfaceiface = gr.Interface(fn=predict,inputs=[1 unmodified linegr.Radio(['Complex Lines', 'Simple Lines'], label='version', value='Simple Lines')],outputs=gr.Image(type="pil"),title=title,examples=examples)iface.launch()
app.py+124-30