Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,170 +1,168 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import torch
|
| 3 |
-
import torchvision.transforms as transforms
|
| 4 |
-
import torchvision.models as models
|
| 5 |
-
import torch.nn as nn
|
| 6 |
-
import torch.optim as optim
|
| 7 |
-
|
| 8 |
-
from PIL import Image
|
| 9 |
-
|
| 10 |
-
import
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
self.
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
self.loss =
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
name = f"
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
elif isinstance(layer, nn.
|
| 77 |
-
name = f"
|
| 78 |
-
|
| 79 |
-
name
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
content_loss
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
style_loss
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
run
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
input_img
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
loss
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
gr.
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
gr.
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
)
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
content_img, style_img
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
)
|
| 169 |
-
|
| 170 |
demo.launch(share=True)
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torchvision.transforms as transforms
|
| 4 |
+
import torchvision.models as models
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.optim as optim
|
| 7 |
+
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import random
|
| 10 |
+
from datasets import load_dataset
|
| 11 |
+
|
| 12 |
+
# β
Device setup
|
| 13 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 14 |
+
|
| 15 |
+
# π¦ Image preprocessing
|
| 16 |
+
transform = transforms.Compose([
|
| 17 |
+
transforms.Resize((512, 512)),
|
| 18 |
+
transforms.ToTensor()
|
| 19 |
+
])
|
| 20 |
+
|
| 21 |
+
def load_image(img):
|
| 22 |
+
image = img.convert("RGB")
|
| 23 |
+
return transform(image).unsqueeze(0).to(device)
|
| 24 |
+
|
| 25 |
+
# π§ NST Core Classes
|
| 26 |
+
class Normalization(nn.Module):
|
| 27 |
+
def __init__(self, mean, std):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.mean = mean.view(-1, 1, 1)
|
| 30 |
+
self.std = std.view(-1, 1, 1)
|
| 31 |
+
def forward(self, img):
|
| 32 |
+
return (img - self.mean) / self.std
|
| 33 |
+
|
| 34 |
+
class ContentLoss(nn.Module):
|
| 35 |
+
def __init__(self, target):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.target = target.detach()
|
| 38 |
+
self.loss = 0
|
| 39 |
+
def forward(self, input):
|
| 40 |
+
self.loss = nn.functional.mse_loss(input, self.target)
|
| 41 |
+
return input
|
| 42 |
+
|
| 43 |
+
def gram_matrix(input):
|
| 44 |
+
b, c, h, w = input.size()
|
| 45 |
+
features = input.view(c, h * w)
|
| 46 |
+
G = torch.mm(features, features.t())
|
| 47 |
+
return G.div(c * h * w)
|
| 48 |
+
|
| 49 |
+
class StyleLoss(nn.Module):
|
| 50 |
+
def __init__(self, target_feature):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.target = gram_matrix(target_feature).detach()
|
| 53 |
+
self.loss = 0
|
| 54 |
+
def forward(self, input):
|
| 55 |
+
G = gram_matrix(input)
|
| 56 |
+
self.loss = nn.functional.mse_loss(G, self.target)
|
| 57 |
+
return input
|
| 58 |
+
|
| 59 |
+
# π§ Model builder
|
| 60 |
+
def get_model_losses(cnn, norm_mean, norm_std, style_img, content_img):
|
| 61 |
+
norm = Normalization(norm_mean, norm_std).to(device)
|
| 62 |
+
model = nn.Sequential(norm)
|
| 63 |
+
|
| 64 |
+
content_losses, style_losses = [], []
|
| 65 |
+
i = 0
|
| 66 |
+
for layer in cnn.children():
|
| 67 |
+
name = None
|
| 68 |
+
if isinstance(layer, nn.Conv2d):
|
| 69 |
+
i += 1
|
| 70 |
+
name = f"conv_{i}"
|
| 71 |
+
elif isinstance(layer, nn.ReLU):
|
| 72 |
+
name = f"relu_{i}"
|
| 73 |
+
layer = nn.ReLU(inplace=False)
|
| 74 |
+
elif isinstance(layer, nn.MaxPool2d):
|
| 75 |
+
name = f"pool_{i}"
|
| 76 |
+
elif isinstance(layer, nn.BatchNorm2d):
|
| 77 |
+
name = f"bn_{i}"
|
| 78 |
+
if name:
|
| 79 |
+
model.add_module(name, layer)
|
| 80 |
+
if name == "conv_4":
|
| 81 |
+
target = model(content_img).detach()
|
| 82 |
+
content_loss = ContentLoss(target)
|
| 83 |
+
model.add_module(f"content_loss_{i}", content_loss)
|
| 84 |
+
content_losses.append(content_loss)
|
| 85 |
+
if name in ["conv_1", "conv_2", "conv_3", "conv_4", "conv_5"]:
|
| 86 |
+
target_feature = model(style_img).detach()
|
| 87 |
+
style_loss = StyleLoss(target_feature)
|
| 88 |
+
model.add_module(f"style_loss_{i}", style_loss)
|
| 89 |
+
style_losses.append(style_loss)
|
| 90 |
+
|
| 91 |
+
for j in range(len(model) - 1, -1, -1):
|
| 92 |
+
if isinstance(model[j], ContentLoss) or isinstance(model[j], StyleLoss):
|
| 93 |
+
break
|
| 94 |
+
return model[:j + 1], style_losses, content_losses
|
| 95 |
+
|
| 96 |
+
# π² Random selector from Hugging Face dataset
|
| 97 |
+
def get_random_image_pair():
|
| 98 |
+
ds = load_dataset("heramb04/Famous-paintings", split="train")
|
| 99 |
+
samples = random.sample(list(ds), 2)
|
| 100 |
+
imgs = [sample["image"].convert("RGB") for sample in samples]
|
| 101 |
+
return imgs[0], imgs[1]
|
| 102 |
+
|
| 103 |
+
# ποΈ NST logic
|
| 104 |
+
def run_nst(content_pil, style_pil, steps=300):
|
| 105 |
+
content = load_image(content_pil)
|
| 106 |
+
style = load_image(style_pil)
|
| 107 |
+
input_img = content.clone().requires_grad_(True)
|
| 108 |
+
|
| 109 |
+
cnn = models.vgg19(pretrained=True).features.to(device).eval()
|
| 110 |
+
norm_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
|
| 111 |
+
norm_std = torch.tensor([0.229, 0.224, 0.225]).to(device)
|
| 112 |
+
|
| 113 |
+
model, style_losses, content_losses = get_model_losses(cnn, norm_mean, norm_std, style, content)
|
| 114 |
+
optimizer = optim.LBFGS([input_img])
|
| 115 |
+
run = [0]
|
| 116 |
+
|
| 117 |
+
while run[0] <= steps:
|
| 118 |
+
def closure():
|
| 119 |
+
input_img.data.clamp_(0, 1)
|
| 120 |
+
optimizer.zero_grad()
|
| 121 |
+
model(input_img)
|
| 122 |
+
style_score = sum(sl.loss for sl in style_losses)
|
| 123 |
+
content_score = sum(cl.loss for cl in content_losses)
|
| 124 |
+
loss = content_score + 1e6 * style_score
|
| 125 |
+
loss.backward()
|
| 126 |
+
run[0] += 1
|
| 127 |
+
return loss
|
| 128 |
+
optimizer.step(closure)
|
| 129 |
+
|
| 130 |
+
output = input_img.clone().detach().cpu().squeeze(0)
|
| 131 |
+
return transforms.ToPILImage()(output)
|
| 132 |
+
|
| 133 |
+
# ποΈ Gradio UI
|
| 134 |
+
with gr.Blocks(title="Neural Style Transfer β A + B = C") as demo:
|
| 135 |
+
gr.Markdown("## π¨ Neural Style Transfer<br>Upload two images OR pick random paintings to remix")
|
| 136 |
+
|
| 137 |
+
with gr.Row():
|
| 138 |
+
with gr.Column():
|
| 139 |
+
content_input = gr.Image(label="πΌοΈ Content Image", type="pil")
|
| 140 |
+
style_input = gr.Image(label="π¨ Style Image", type="pil")
|
| 141 |
+
steps_slider = gr.Slider(100, 500, value=300, step=50, label="Optimization Steps")
|
| 142 |
+
upload_button = gr.Button("β¨ Stylize Uploaded Images")
|
| 143 |
+
random_button = gr.Button("π² Pick Random & Generate")
|
| 144 |
+
|
| 145 |
+
with gr.Column():
|
| 146 |
+
gr.Markdown("### π§ A + B = C")
|
| 147 |
+
content_preview = gr.Image(label="A: Content", interactive=False)
|
| 148 |
+
style_preview = gr.Image(label="B: Style", interactive=False)
|
| 149 |
+
output_preview = gr.Image(label="C: Stylized Output", interactive=False)
|
| 150 |
+
|
| 151 |
+
upload_button.click(
|
| 152 |
+
fn=run_nst,
|
| 153 |
+
inputs=[content_input, style_input, steps_slider],
|
| 154 |
+
outputs=output_preview
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
def random_nst_wrapper(steps):
|
| 158 |
+
content_img, style_img = get_random_image_pair()
|
| 159 |
+
result = run_nst(content_img, style_img, steps)
|
| 160 |
+
return content_img, style_img, result
|
| 161 |
+
|
| 162 |
+
random_button.click(
|
| 163 |
+
fn=random_nst_wrapper,
|
| 164 |
+
inputs=[steps_slider],
|
| 165 |
+
outputs=[content_preview, style_preview, output_preview]
|
| 166 |
+
)
|
| 167 |
+
|
|
|
|
|
|
|
| 168 |
demo.launch(share=True)
|