File size: 8,307 Bytes
1eaf723
659d1e7
dbe4fe6
 
 
 
 
6063bf9
18610bc
659d1e7
 
 
 
dbe4fe6
 
18610bc
dbe4fe6
18610bc
 
 
 
 
 
dbe4fe6
 
18610bc
dbe4fe6
 
 
18610bc
 
dbe4fe6
18610bc
 
 
 
dbe4fe6
18610bc
 
dbe4fe6
 
18610bc
dbe4fe6
 
18610bc
 
 
 
dbe4fe6
 
 
 
 
 
 
 
 
 
 
18610bc
dbe4fe6
 
 
 
cb897c1
 
dbe4fe6
 
18610bc
 
 
dbe4fe6
 
18610bc
dbe4fe6
 
cb897c1
dbe4fe6
feaa03b
dbe4fe6
 
 
 
18610bc
 
659d1e7
 
 
3c69e99
fa3cf6d
18610bc
2fb1494
34974b2
18610bc
2fb1494
3c69e99
fa3cf6d
2fb1494
3c69e99
dbe4fe6
18610bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe4fe6
18610bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import os
from huggingface_hub import hf_hub_download
os.system("pip -qq install facenet_pytorch")
from facenet_pytorch import MTCNN
from torchvision import transforms
import torch, PIL
import gradio as gr

# Download models
modelarcanev4 = hf_hub_download(repo_id="akhaliq/ArcaneGANv0.4", filename="ArcaneGANv0.4.jit")
modelarcanev3 = hf_hub_download(repo_id="akhaliq/ArcaneGANv0.3", filename="ArcaneGANv0.3.jit")
modelarcanev2 = hf_hub_download(repo_id="akhaliq/ArcaneGANv0.2", filename="ArcaneGANv0.2.jit")

mtcnn = MTCNN(image_size=256, margin=80)

# Face detection
def detect(img):
    batch_boxes, batch_probs, batch_points = mtcnn.detect(img, landmarks=True)
    if not mtcnn.keep_all:
        batch_boxes, batch_probs, batch_points = mtcnn.select_boxes(
            batch_boxes, batch_probs, batch_points, img, method=mtcnn.selection_method
        )
    return batch_boxes, batch_points

def makeEven(_x):
    return _x if (_x % 2 == 0) else _x+1

def scale(boxes, _img, max_res=1_500_000, target_face=256, fixed_ratio=0, max_upscale=2, VERBOSE=False):
    x, y = _img.size
    ratio = 2
    
    if (boxes is not None):
        if len(boxes)>0:
            ratio = target_face/max(boxes[0][2:]-boxes[0][:2])
            ratio = min(ratio, max_upscale)
    
    if fixed_ratio>0:
        ratio = fixed_ratio
    
    x*=ratio
    y*=ratio
    
    res = x*y
    if res > max_res:
        ratio = pow(res/max_res,1/2)
        x=int(x/ratio)
        y=int(y/ratio)
    
    x = makeEven(int(x))
    y = makeEven(int(y))
    size = (x, y)
    return _img.resize(size)

def scale_by_face_size(_img, max_res=1_500_000, target_face=256, fix_ratio=0, max_upscale=2, VERBOSE=False):
    boxes = None
    boxes, _ = detect(_img)
    img_resized = scale(boxes, _img, max_res, target_face, fix_ratio, max_upscale, VERBOSE)
    return img_resized

# Image processing setup
size = 256
means = [0.485, 0.456, 0.406]
stds = [0.229, 0.224, 0.225]

t_stds = torch.tensor(stds).cuda().half()[:,None,None]
t_means = torch.tensor(means).cuda().half()[:,None,None]

img_transforms = transforms.Compose([                        
    transforms.ToTensor(),
    transforms.Normalize(means,stds)
])
 
def tensor2im(var):
    return var.mul(t_stds).add(t_means).mul(255.).clamp(0,255).permute(1,2,0)

def proc_pil_img(input_image, model):
    transformed_image = img_transforms(input_image)[None,...].cuda().half()
    with torch.no_grad():
        result_image = model(transformed_image)[0]
        output_image = tensor2im(result_image)
        output_image = output_image.detach().cpu().numpy().astype('uint8')
        output_image = PIL.Image.fromarray(output_image)
    return output_image

# Load models
modelv4 = torch.jit.load(modelarcanev4).eval().cuda().half()
modelv3 = torch.jit.load(modelarcanev3).eval().cuda().half()
modelv2 = torch.jit.load(modelarcanev2).eval().cuda().half()

def process(im, version):
    if version == 'v0.4 (Recommended)':
        im = scale_by_face_size(im, target_face=256, max_res=1_500_000, max_upscale=1)
        res = proc_pil_img(im, modelv4)
    elif version == 'v0.3':
        im = scale_by_face_size(im, target_face=256, max_res=1_500_000, max_upscale=1)
        res = proc_pil_img(im, modelv3)
    else:
        im = scale_by_face_size(im, target_face=256, max_res=1_500_000, max_upscale=1)
        res = proc_pil_img(im, modelv2)
    return res

# Custom theme
custom_theme = gr.themes.Soft(
    primary_hue="blue",
    secondary_hue="indigo",
    neutral_hue="slate",
    font=gr.themes.GoogleFont("Inter"),
    text_size="lg",
    spacing_size="md",
    radius_size="lg"
).set(
    button_primary_background_fill="*primary_600",
    button_primary_background_fill_hover="*primary_700",
    block_title_text_weight="600",
    block_border_width="2px",
    block_shadow="*shadow_drop_lg",
)

# Custom CSS for mobile-friendly design
custom_css = """
.gradio-container {
    max-width: 1200px !important;
    margin: auto !important;
}

#header {
    text-align: center;
    margin-bottom: 2rem;
}

#header h1 {
    font-size: 2.5rem;
    font-weight: 700;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    margin-bottom: 0.5rem;
}

#description {
    font-size: 1.1rem;
    color: #64748b;
    margin-bottom: 1rem;
}

.input-column, .output-column {
    border-radius: 16px;
    padding: 1.5rem;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
}

@media (max-width: 768px) {
    #header h1 {
        font-size: 2rem;
    }
    
    #description {
        font-size: 1rem;
    }
    
    .input-column, .output-column {
        padding: 1rem;
    }
}

#footer {
    text-align: center;
    margin-top: 2rem;
    padding: 1.5rem;
    border-top: 2px solid #e2e8f0;
}

#footer a {
    color: #667eea;
    text-decoration: none;
    font-weight: 600;
}

#footer a:hover {
    color: #764ba2;
    text-decoration: underline;
}

.example-container {
    margin-top: 1rem;
}
"""

# Build the interface
with gr.Blocks() as demo:
    
    # Header
    with gr.Column(elem_id="header"):
        gr.Markdown(
            """
            # 🎨 ArcaneGAN
            ### Transform Your Photos into Arcane-Style Art
            Upload a portrait and watch it transform into the stunning visual style of Netflix's Arcane series.
            """
        )
        gr.Markdown(
            "[Built with anycoder](https://huggingface.co/spaces/akhaliq/anycoder)",
            elem_id="anycoder-link"
        )
    
    # Main content
    with gr.Row(equal_height=True):
        # Input column
        with gr.Column(scale=1, elem_classes="input-column"):
            gr.Markdown("### πŸ“€ Upload Your Photo")
            input_image = gr.Image(
                type="pil",
                label="Input Image",
                sources=["upload", "webcam", "clipboard"],
                height=400
            )
            
            version_selector = gr.Radio(
                choices=['v0.4 (Recommended)', 'v0.3', 'v0.2'],
                value='v0.4 (Recommended)',
                label="Model Version",
                info="v0.4 offers the best quality"
            )
            
            transform_btn = gr.Button(
                "✨ Transform to Arcane Style",
                variant="primary",
                size="lg"
            )
        
        # Output column
        with gr.Column(scale=1, elem_classes="output-column"):
            gr.Markdown("### 🎭 Arcane-Style Result")
            output_image = gr.Image(
                type="pil",
                label="Transformed Image",
                height=400,
                buttons=["download", "share"]
            )
    
    # Examples
    with gr.Row():
        gr.Examples(
            examples=[
                ['bill.png', 'v0.3'],
                ['keanu.png', 'v0.4 (Recommended)'],
                ['will.jpeg', 'v0.4 (Recommended)']
            ],
            inputs=[input_image, version_selector],
            outputs=output_image,
            fn=process,
            cache_examples=True,
            label="Try These Examples",
            examples_per_page=3
        )
    
    # Footer
    with gr.Column(elem_id="footer"):
        gr.Markdown(
            """
            ---
            **ArcaneGAN** by [Alexander S](https://twitter.com/devdef) | 
            [GitHub Repository](https://github.com/Sxela/ArcaneGAN) | 
            [Original Space](https://huggingface.co/spaces/akhaliq/ArcaneGAN)
            
            <div style='margin-top: 1rem;'>
                <img src='https://visitor-badge.glitch.me/badge?page_id=akhaliq_arcanegan' alt='visitor badge'>
            </div>
            """
        )
    
    # Event handlers
    transform_btn.click(
        fn=process,
        inputs=[input_image, version_selector],
        outputs=output_image,
        api_name="transform"
    )
    
    input_image.upload(
        fn=process,
        inputs=[input_image, version_selector],
        outputs=output_image
    )

# Launch with Gradio 6 syntax
demo.launch(
    theme=custom_theme,
    css=custom_css,
    footer_links=[
        {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
    ]
)