adowu commited on
Commit
033b7bc
·
verified ·
1 Parent(s): f44c6cf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -58
app.py CHANGED
@@ -1,87 +1,71 @@
1
  import torch
2
  import torch.nn as nn
 
 
3
  import gradio as gr
4
- import numpy as np
5
- from huggingface_hub.fastai_utils import from_pretrained_fastai
6
- from fastai.vision.all import *
7
- from pathlib import Path
8
 
9
  # ================================================
10
- # STUBS FOR CUSTOM CLASSES / FUNCTIONS
11
  # ================================================
12
 
13
- # Functions
14
- def _inner(*args, **kwargs): return None
15
- def style_loss(*args, **kwargs): return None
16
- def act_loss(*args, **kwargs): return None
17
-
18
- # Layers
19
- class ReflectionLayer(nn.Module):
20
- def __init__(self): super().__init__()
21
- def forward(self, x): return x
22
-
23
- class ConvLayer(nn.Module):
24
- def __init__(self): super().__init__()
25
- def forward(self, x): return x
26
-
27
- class ResidualBlock(nn.Module):
28
- def __init__(self): super().__init__()
29
- def forward(self, x): return x
30
-
31
- class UpsampleConvLayer(nn.Module):
32
- def __init__(self): super().__init__()
33
- def forward(self, x): return x
34
-
35
- class TransformerNet(nn.Module):
36
- def __init__(self): super().__init__()
37
- def forward(self, x): return x
38
-
39
- class FeatureLoss:
40
- def __init__(self, *args, **kwargs): pass
41
 
42
  # ================================================
43
- # LOAD FASTAI MODEL
44
  # ================================================
45
 
46
- REPO_ID = "hugginglearners/fastai-style-transfer"
47
- learner = from_pretrained_fastai(REPO_ID)
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  # ================================================
50
- # INFERENCE FUNCTION
51
  # ================================================
52
 
53
- def infer(img):
54
- # Convert to PILImage if needed
55
- if not isinstance(img, PILImage):
56
- img = PILImage.create(img)
57
-
58
- pred = learner.predict(img)
59
- image = pred[0].numpy()
60
- image = image.transpose((1, 2, 0)) # CHW -> HWC
61
- image = np.clip(image*255, 0, 255).astype(np.uint8)
62
- return image
63
 
64
  # ================================================
65
  # GRADIO INTERFACE
66
  # ================================================
67
 
68
- EXAMPLES_PATH = Path("./examples")
69
- examples = [str(EXAMPLES_PATH / f.name) for f in EXAMPLES_PATH.iterdir()]
70
-
71
- title = "🎨 FastAI Style Transfer"
72
- description = "Transform images using a neural style transfer model."
73
- article = 'Author: <a href="https://huggingface.co/geninhu">Nhu Hoang</a>.'
74
 
75
  app = gr.Interface(
76
  fn=infer,
77
- inputs=gr.Image(type="pil", label="Upload Image"),
 
 
 
78
  outputs=gr.Image(label="Stylized Image"),
79
- examples=examples,
80
  title=title,
81
  description=description,
82
- article=article,
83
- allow_flagging="never",
84
- cache_examples=False
85
  )
86
 
87
  if __name__ == "__main__":
 
1
  import torch
2
  import torch.nn as nn
3
+ import torchvision.transforms as transforms
4
+ from PIL import Image
5
  import gradio as gr
6
+ from torchvision.utils import save_image
 
 
 
7
 
8
  # ================================================
9
+ # FAST NEURAL STYLE MODEL (AdaIN) - Pytorch Hub
10
  # ================================================
11
 
12
+ # Tutaj pobieramy model z PyTorch Hub (dynamic style transfer)
13
+ # Uwaga: model pobiera content + style image
14
+ model = torch.hub.load('pytorch/examples', 'fast_neural_style', source='github', model='candy') # przykładowy styl
15
+ model.eval()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  # ================================================
18
+ # UTILS
19
  # ================================================
20
 
21
+ def preprocess(img, size=512):
22
+ """Konwersja PIL -> Tensor"""
23
+ transform = transforms.Compose([
24
+ transforms.Resize(size),
25
+ transforms.ToTensor(),
26
+ transforms.Lambda(lambda x: x.mul(255))
27
+ ])
28
+ img_t = transform(img).unsqueeze(0) # dodaj batch dim
29
+ return img_t
30
+
31
+ def postprocess(tensor):
32
+ """Tensor -> PIL Image"""
33
+ tensor = tensor.clamp(0, 255).squeeze(0)
34
+ tensor = tensor / 255
35
+ return transforms.ToPILImage()(tensor)
36
 
37
  # ================================================
38
+ # INFERENCE
39
  # ================================================
40
 
41
+ def infer(content_img, style_img):
42
+ # Preprocess
43
+ content = preprocess(content_img)
44
+ style = preprocess(style_img)
45
+
46
+ # Użyj modelu dynamic style transfer
47
+ with torch.no_grad():
48
+ output = model(content, style) # content + style
49
+
50
+ return postprocess(output)
51
 
52
  # ================================================
53
  # GRADIO INTERFACE
54
  # ================================================
55
 
56
+ title = "🎨 Dynamic Neural Style Transfer"
57
+ description = "Upload a content image and a style image to apply style transfer dynamically."
 
 
 
 
58
 
59
  app = gr.Interface(
60
  fn=infer,
61
+ inputs=[
62
+ gr.Image(type="pil", label="Content Image"),
63
+ gr.Image(type="pil", label="Style Image")
64
+ ],
65
  outputs=gr.Image(label="Stylized Image"),
 
66
  title=title,
67
  description=description,
68
+ allow_flagging="never"
 
 
69
  )
70
 
71
  if __name__ == "__main__":