Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,114 +1,299 @@
|
|
| 1 |
"""
|
| 2 |
-
hf_space/app.py
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
or:
|
| 9 |
-
python hf_space/app.py --ckpt ./paintpath_best.pt
|
| 10 |
-
2. Directly on Hugging Face Spaces:
|
| 11 |
-
Set environment variable `HF_MODEL_REPO="your-username/paintpath-net"`
|
| 12 |
-
(or place `hf_model/` inside the Space repo) and push!
|
| 13 |
"""
|
| 14 |
|
| 15 |
import argparse
|
| 16 |
import os
|
| 17 |
-
import
|
| 18 |
from pathlib import Path
|
| 19 |
-
from typing import List
|
| 20 |
|
| 21 |
import cv2
|
| 22 |
import gradio as gr
|
| 23 |
import numpy as np
|
|
|
|
| 24 |
import torch
|
|
|
|
|
|
|
| 25 |
from PIL import Image, ImageDraw
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
# Support running both from project root and standalone inside a Hugging Face Space
|
| 28 |
-
HERE = Path(__file__).resolve().parent
|
| 29 |
-
ROOT = HERE.parent
|
| 30 |
-
for p in (str(ROOT), str(HERE)):
|
| 31 |
-
if p not in sys.path:
|
| 32 |
-
sys.path.insert(0, p)
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 40 |
MODEL = None
|
| 41 |
-
MODEL_STATUS = "
|
| 42 |
|
| 43 |
|
| 44 |
def load_paintpath_model(model_dir: str = "", ckpt_path: str = "", hf_repo: str = ""):
|
| 45 |
global MODEL, MODEL_STATUS
|
|
|
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
MODEL = m
|
| 51 |
-
MODEL_STATUS = f"Loaded Hugging Face model from: {model_dir} ({DEVICE})"
|
| 52 |
return
|
| 53 |
|
| 54 |
-
# 2. Hugging Face Hub Repo ID (for Hugging Face Spaces!)
|
| 55 |
if hf_repo:
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
MODEL_STATUS = f"Loaded Hugging Face Hub model: {hf_repo} ({DEVICE})"
|
| 59 |
return
|
| 60 |
|
| 61 |
-
# 3. Direct PyTorch checkpoint (`paintpath_best.pt`)
|
| 62 |
if ckpt_path and Path(ckpt_path).exists():
|
| 63 |
m = PaintPathNet(pretrained=False).to(DEVICE)
|
| 64 |
ckpt = torch.load(ckpt_path, map_location=DEVICE)
|
| 65 |
m.load_state_dict(ckpt["model"] if "model" in ckpt else ckpt)
|
| 66 |
-
m.eval()
|
| 67 |
-
MODEL = m
|
| 68 |
MODEL_STATUS = f"Loaded checkpoint: {ckpt_path} ({DEVICE})"
|
| 69 |
return
|
| 70 |
|
| 71 |
MODEL = None
|
| 72 |
-
MODEL_STATUS =
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
def add_proportion_grid(img_rgb: np.ndarray, grid_n: int = 4) -> np.ndarray:
|
| 76 |
-
"""Overlay a subtle artist proportion grid (e.g. 4x4) on Stage 1 Sketch."""
|
| 77 |
-
out = img_rgb.copy()
|
| 78 |
-
h, w = out.shape[:2]
|
| 79 |
-
color = (160, 185, 220)
|
| 80 |
-
for i in range(1, grid_n):
|
| 81 |
-
y = int(round(h * i / grid_n))
|
| 82 |
-
x = int(round(w * i / grid_n))
|
| 83 |
-
cv2.line(out, (0, y), (w, y), color, 1, cv2.LINE_AA)
|
| 84 |
-
cv2.line(out, (x, 0), (x, h), color, 1, cv2.LINE_AA)
|
| 85 |
-
return out
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
def render_palette_card(palette: List[PaletteColor]) -> np.ndarray:
|
| 89 |
-
card_w, row_h = 740, 52
|
| 90 |
-
card_h = 44 + len(palette) * row_h
|
| 91 |
-
im = Image.new("RGB", (card_w, card_h), (249, 247, 243))
|
| 92 |
-
draw = ImageDraw.Draw(im)
|
| 93 |
-
draw.text((16, 12), "Your Simple Physical Palette & Tube Mixing Guide (Kubelka-Munk)", fill=(30, 30, 30))
|
| 94 |
-
|
| 95 |
-
for i, c in enumerate(palette):
|
| 96 |
-
y0 = 40 + i * row_h
|
| 97 |
-
draw.rectangle([16, y0 + 5, 82, y0 + row_h - 5], fill=c.rgb, outline=(60, 60, 60), width=1)
|
| 98 |
-
recipe_str = " + ".join(f"{pct}% {name}" for name, pct in c.mixing_recipe)
|
| 99 |
-
draw.text((96, y0 + 6), f"Color #{c.index + 1} {c.hex} ({c.proportion * 100:.1f}%)", fill=(25, 25, 25))
|
| 100 |
-
draw.text((96, y0 + 26), f"Mix: {recipe_str}", fill=(75, 75, 75))
|
| 101 |
-
return np.array(im)
|
| 102 |
|
| 103 |
|
| 104 |
@torch.no_grad()
|
| 105 |
def predict_roadmap(input_img: np.ndarray, num_colors: int, show_grid: bool, inference_size: int):
|
| 106 |
if input_img is None:
|
| 107 |
return None, None, None, None, None, "لطفاً یک تصویر نقاشی آپلود کنید."
|
|
|
|
|
|
|
| 108 |
|
| 109 |
clean = auto_crop_borders(input_img)
|
| 110 |
h, w = clean.shape[:2]
|
| 111 |
-
# Keep aspect ratio cleanly padded/resized to multiple of 32 for ConvNeXt U-Net
|
| 112 |
scale = inference_size / max(h, w)
|
| 113 |
nw = max(64, (int(round(w * scale)) // 32) * 32)
|
| 114 |
nh = max(64, (int(round(h * scale)) // 32) * 32)
|
|
@@ -117,22 +302,19 @@ def predict_roadmap(input_img: np.ndarray, num_colors: int, show_grid: bool, inf
|
|
| 117 |
palette = extract_physical_palette(resized, k=int(num_colors))
|
| 118 |
pal_card = render_palette_card(palette)
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
gpu_name = torch.cuda.get_device_name(0) if DEVICE.type == "cuda" else ""
|
| 124 |
-
use_amp = (DEVICE.type == "cuda") and ("1650" not in gpu_name and "1660" not in gpu_name)
|
| 125 |
-
for s_idx in range(4):
|
| 126 |
-
st = torch.tensor([s_idx], dtype=torch.long, device=DEVICE)
|
| 127 |
-
with torch.amp.autocast("cuda", enabled=use_amp, dtype=torch.float16):
|
| 128 |
-
pred = MODEL(inp, st)
|
| 129 |
-
arr = (pred[0].float().clamp(0, 1).permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8)
|
| 130 |
-
stages_out.append(arr)
|
| 131 |
-
s1, s2, s3, s4 = stages_out
|
| 132 |
-
else:
|
| 133 |
-
st_dict = generate_all_stages(resized)
|
| 134 |
-
s1, s2, s3, s4 = st_dict[1], st_dict[2], st_dict[3], st_dict[4]
|
| 135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
if show_grid:
|
| 137 |
s1 = add_proportion_grid(s1, grid_n=4)
|
| 138 |
|
|
@@ -146,27 +328,27 @@ def build_ui():
|
|
| 146 |
# 🎨 PaintPath — AI Teaches Humans to Paint
|
| 147 |
*«همیشه انسان کار را برای هوش مصنوعی ساده میکند؛ این بار هوش مصنوعی هنر را برای انسان ساده میکند تا نقاش بشود!»*
|
| 148 |
|
| 149 |
-
|
| 150 |
"""
|
| 151 |
)
|
| 152 |
|
| 153 |
with gr.Row():
|
| 154 |
with gr.Column(scale=1):
|
| 155 |
-
in_img = gr.Image(type="numpy", label="نقاشی
|
| 156 |
-
num_colors = gr.Slider(6, 12, value=8, step=1, label="تعداد رنگ
|
| 157 |
-
show_grid = gr.Checkbox(value=True, label="
|
| 158 |
-
inf_size = gr.Slider(256,
|
| 159 |
-
run_btn = gr.Button("✨
|
| 160 |
-
status = gr.Textbox(label="
|
| 161 |
with gr.Column(scale=1):
|
| 162 |
-
pal_out = gr.Image(label="🎨
|
| 163 |
|
| 164 |
-
gr.Markdown("### 🗺️
|
| 165 |
with gr.Row():
|
| 166 |
-
s1_out = gr.Image(label="
|
| 167 |
-
s2_out = gr.Image(label="
|
| 168 |
-
s3_out = gr.Image(label="
|
| 169 |
-
s4_out = gr.Image(label="
|
| 170 |
|
| 171 |
run_btn.click(
|
| 172 |
fn=predict_roadmap,
|
|
@@ -176,7 +358,14 @@ def build_ui():
|
|
| 176 |
return demo
|
| 177 |
|
| 178 |
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
parser = argparse.ArgumentParser()
|
| 181 |
parser.add_argument("--model-dir", type=str, default=str(HERE / "hf_model"))
|
| 182 |
parser.add_argument("--ckpt", type=str, default="")
|
|
@@ -187,15 +376,3 @@ def main():
|
|
| 187 |
load_paintpath_model(args.model_dir, args.ckpt, args.hf_repo)
|
| 188 |
demo = build_ui()
|
| 189 |
demo.launch(server_name="127.0.0.1", server_port=args.port, inbrowser=True)
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
# Auto-load when launched directly by Hugging Face Spaces (`gradio` imports `demo`)
|
| 193 |
-
if os.environ.get("SPACE_ID"):
|
| 194 |
-
load_paintpath_model(
|
| 195 |
-
model_dir=str(HERE / "hf_model"),
|
| 196 |
-
hf_repo=os.environ.get("HF_MODEL_REPO", ""),
|
| 197 |
-
)
|
| 198 |
-
demo = build_ui()
|
| 199 |
-
demo.launch()
|
| 200 |
-
elif __name__ == "__main__":
|
| 201 |
-
main()
|
|
|
|
| 1 |
"""
|
| 2 |
+
hf_space/app.py — 100% Self-Contained Hugging Face Space & Local Runner for PaintPathNet!
|
| 3 |
+
(No external `src/` folder required — just upload `app.py`, `requirements.txt`, and `README.md`!)
|
| 4 |
+
|
| 5 |
+
Environment variables (set in Hugging Face Space Settings -> Variables & Secrets):
|
| 6 |
+
- HF_MODEL_REPO : e.g. "your-username/paintpath-net"
|
| 7 |
+
- HF_TOKEN : (only needed if your model repo is Private)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
"""
|
| 9 |
|
| 10 |
import argparse
|
| 11 |
import os
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
from pathlib import Path
|
| 14 |
+
from typing import Dict, List, Tuple
|
| 15 |
|
| 16 |
import cv2
|
| 17 |
import gradio as gr
|
| 18 |
import numpy as np
|
| 19 |
+
import timm
|
| 20 |
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
from PIL import Image, ImageDraw
|
| 24 |
+
from scipy.optimize import minimize
|
| 25 |
+
from sklearn.cluster import KMeans
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
from huggingface_hub import PyTorchModelHubMixin
|
| 29 |
+
except ImportError:
|
| 30 |
+
class PyTorchModelHubMixin:
|
| 31 |
+
pass
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# ============================================================
|
| 35 |
+
# 1. PaintPathNet Model Architecture (Hugging Face Standard)
|
| 36 |
+
# ============================================================
|
| 37 |
+
class FiLMResBlock(nn.Module):
|
| 38 |
+
def __init__(self, in_ch: int, out_ch: int, cond_dim: int):
|
| 39 |
+
super().__init__()
|
| 40 |
+
num_groups = next(g for g in (32, 16, 8, 4, 2, 1) if out_ch % g == 0)
|
| 41 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, kernel_size=3, padding=1, bias=False)
|
| 42 |
+
self.norm1 = nn.GroupNorm(num_groups, out_ch)
|
| 43 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, kernel_size=3, padding=1, bias=False)
|
| 44 |
+
self.norm2 = nn.GroupNorm(num_groups, out_ch)
|
| 45 |
+
self.film = nn.Linear(cond_dim, out_ch * 2)
|
| 46 |
+
nn.init.zeros_(self.film.weight)
|
| 47 |
+
nn.init.zeros_(self.film.bias)
|
| 48 |
+
self.skip = nn.Conv2d(in_ch, out_ch, kernel_size=1) if in_ch != out_ch else nn.Identity()
|
| 49 |
+
|
| 50 |
+
def forward(self, x: torch.Tensor, cond: torch.Tensor) -> torch.Tensor:
|
| 51 |
+
h = F.gelu(self.norm1(self.conv1(x)))
|
| 52 |
+
gamma, beta = self.film(cond).chunk(2, dim=-1)
|
| 53 |
+
h = self.norm2(self.conv2(h))
|
| 54 |
+
h = h * (1.0 + gamma[:, :, None, None]) + beta[:, :, None, None]
|
| 55 |
+
return F.gelu(h + self.skip(x))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class PaintPathNet(nn.Module, PyTorchModelHubMixin):
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
backbone: str = "convnext_small.fb_in22k_ft_in1k",
|
| 62 |
+
pretrained: bool = False,
|
| 63 |
+
num_stages: int = 4,
|
| 64 |
+
cond_dim: int = 256,
|
| 65 |
+
):
|
| 66 |
+
super().__init__()
|
| 67 |
+
self.backbone = backbone
|
| 68 |
+
self.num_stages = num_stages
|
| 69 |
+
self.cond_dim = cond_dim
|
| 70 |
+
|
| 71 |
+
self.encoder = timm.create_model(
|
| 72 |
+
backbone,
|
| 73 |
+
pretrained=pretrained,
|
| 74 |
+
features_only=True,
|
| 75 |
+
out_indices=(0, 1, 2, 3),
|
| 76 |
+
)
|
| 77 |
+
chs = self.encoder.feature_info.channels()
|
| 78 |
+
|
| 79 |
+
self.stage_emb = nn.Sequential(
|
| 80 |
+
nn.Embedding(num_stages, cond_dim),
|
| 81 |
+
nn.Linear(cond_dim, cond_dim),
|
| 82 |
+
nn.GELU(),
|
| 83 |
+
nn.Linear(cond_dim, cond_dim),
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
self.bottleneck = FiLMResBlock(chs[3], 512, cond_dim)
|
| 87 |
+
self.dec3 = FiLMResBlock(512 + chs[2], 256, cond_dim)
|
| 88 |
+
self.dec2 = FiLMResBlock(256 + chs[1], 128, cond_dim)
|
| 89 |
+
self.dec1 = FiLMResBlock(128 + chs[0], 96, cond_dim)
|
| 90 |
+
|
| 91 |
+
self.up_half = FiLMResBlock(96, 64, cond_dim)
|
| 92 |
+
self.up_full = FiLMResBlock(64 + 3, 48, cond_dim)
|
| 93 |
+
self.out_head = nn.Sequential(
|
| 94 |
+
nn.Conv2d(48, 32, kernel_size=3, padding=1),
|
| 95 |
+
nn.GELU(),
|
| 96 |
+
nn.Conv2d(32, 3, kernel_size=1),
|
| 97 |
+
nn.Sigmoid(),
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
self.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
|
| 101 |
+
self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
|
| 102 |
+
|
| 103 |
+
def forward(self, img: torch.Tensor, stage_idx: torch.Tensor) -> torch.Tensor:
|
| 104 |
+
x_norm = (img - self.mean) / self.std
|
| 105 |
+
f1, f2, f3, f4 = self.encoder(x_norm)
|
| 106 |
+
cond = self.stage_emb(stage_idx)
|
| 107 |
+
|
| 108 |
+
h = self.bottleneck(f4, cond)
|
| 109 |
+
h = F.interpolate(h, size=f3.shape[-2:], mode="bilinear", align_corners=False)
|
| 110 |
+
h = self.dec3(torch.cat([h, f3], dim=1), cond)
|
| 111 |
+
|
| 112 |
+
h = F.interpolate(h, size=f2.shape[-2:], mode="bilinear", align_corners=False)
|
| 113 |
+
h = self.dec2(torch.cat([h, f2], dim=1), cond)
|
| 114 |
+
|
| 115 |
+
h = F.interpolate(h, size=f1.shape[-2:], mode="bilinear", align_corners=False)
|
| 116 |
+
h = self.dec1(torch.cat([h, f1], dim=1), cond)
|
| 117 |
+
|
| 118 |
+
H, W = img.shape[-2], img.shape[-1]
|
| 119 |
+
h = F.interpolate(h, size=(H // 2, W // 2), mode="bilinear", align_corners=False)
|
| 120 |
+
h = self.up_half(h, cond)
|
| 121 |
+
|
| 122 |
+
h = F.interpolate(h, size=(H, W), mode="bilinear", align_corners=False)
|
| 123 |
+
h = self.up_full(torch.cat([h, img], dim=1), cond)
|
| 124 |
+
return self.out_head(h)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# ============================================================
|
| 128 |
+
# 2. Physical Pigment Palette & Kubelka-Munk Mixing Recipes
|
| 129 |
+
# ============================================================
|
| 130 |
+
ARTIST_TUBES: Dict[str, Tuple[int, int, int]] = {
|
| 131 |
+
"Titanium White": (245, 245, 242),
|
| 132 |
+
"Ivory Black": (28, 28, 30),
|
| 133 |
+
"Ultramarine Blue": (25, 45, 145),
|
| 134 |
+
"Cadmium Red": (208, 38, 32),
|
| 135 |
+
"Cadmium Yellow": (242, 200, 28),
|
| 136 |
+
"Yellow Ochre": (198, 146, 58),
|
| 137 |
+
"Burnt Umber": (84, 52, 34),
|
| 138 |
+
"Viridian Green": (34, 118, 88),
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _srgb_to_linear(rgb01: np.ndarray) -> np.ndarray:
|
| 143 |
+
return np.where(rgb01 <= 0.04045, rgb01 / 12.92, ((rgb01 + 0.055) / 1.055) ** 2.4)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _linear_to_ks(r: np.ndarray) -> np.ndarray:
|
| 147 |
+
r = np.clip(r, 1e-3, 0.999)
|
| 148 |
+
return ((1.0 - r) ** 2) / (2.0 * r)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def solve_tube_recipe(target_rgb: Tuple[int, int, int], max_tubes: int = 3) -> List[Tuple[str, int]]:
|
| 152 |
+
names = list(ARTIST_TUBES.keys())
|
| 153 |
+
tube_lin = _srgb_to_linear(np.array([ARTIST_TUBES[n] for n in names], dtype=np.float64) / 255.0)
|
| 154 |
+
tube_ks = _linear_to_ks(tube_lin)
|
| 155 |
+
tgt_lin = _srgb_to_linear(np.array(target_rgb, dtype=np.float64) / 255.0)
|
| 156 |
+
|
| 157 |
+
def _fit(sub_ks: np.ndarray) -> np.ndarray:
|
| 158 |
+
m = len(sub_ks)
|
| 159 |
+
def loss_fn(w):
|
| 160 |
+
ks = np.maximum(w @ sub_ks, 1e-4)
|
| 161 |
+
pred_r = 1.0 + ks - np.sqrt(ks * ks + 2.0 * ks)
|
| 162 |
+
return float(np.sum((pred_r - tgt_lin) ** 2))
|
| 163 |
+
res = minimize(
|
| 164 |
+
loss_fn,
|
| 165 |
+
x0=np.ones(m, dtype=np.float64) / m,
|
| 166 |
+
bounds=[(0.0, 1.0)] * m,
|
| 167 |
+
constraints={"type": "eq", "fun": lambda w: np.sum(w) - 1.0},
|
| 168 |
+
method="SLSQP",
|
| 169 |
+
options={"ftol": 1e-9, "maxiter": 150},
|
| 170 |
+
)
|
| 171 |
+
w = np.maximum(res.x, 0.0)
|
| 172 |
+
return w / (w.sum() + 1e-12)
|
| 173 |
+
|
| 174 |
+
w = _fit(tube_ks)
|
| 175 |
+
top_idx = np.argsort(w)[::-1][:max_tubes]
|
| 176 |
+
sw = _fit(tube_ks[top_idx])
|
| 177 |
+
|
| 178 |
+
recipe = [(names[idx], int(round(weight * 100))) for idx, weight in zip(top_idx, sw) if int(round(weight * 100)) >= 5]
|
| 179 |
+
if recipe:
|
| 180 |
+
total = sum(p for _, p in recipe)
|
| 181 |
+
if total != 100:
|
| 182 |
+
recipe[0] = (recipe[0][0], recipe[0][1] + (100 - total))
|
| 183 |
+
return recipe
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
@dataclass
|
| 187 |
+
class PaletteColor:
|
| 188 |
+
index: int
|
| 189 |
+
rgb: Tuple[int, int, int]
|
| 190 |
+
hex: str
|
| 191 |
+
proportion: float
|
| 192 |
+
mixing_recipe: List[Tuple[str, int]]
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def extract_physical_palette(image_rgb: np.ndarray, k: int = 8, seed: int = 42) -> List[PaletteColor]:
|
| 196 |
+
small = cv2.resize(image_rgb, (128, 128), interpolation=cv2.INTER_AREA)
|
| 197 |
+
lab = cv2.cvtColor(small, cv2.COLOR_RGB2LAB).reshape(-1, 3).astype(np.float32)
|
| 198 |
+
km = KMeans(n_clusters=k, n_init=5, random_state=seed)
|
| 199 |
+
labels = km.fit_predict(lab)
|
| 200 |
+
centers_rgb = cv2.cvtColor(np.clip(km.cluster_centers_, 0, 255).astype(np.uint8).reshape(1, k, 3), cv2.COLOR_LAB2RGB).reshape(k, 3)
|
| 201 |
+
props = np.bincount(labels, minlength=k).astype(np.float64)
|
| 202 |
+
props /= props.sum()
|
| 203 |
+
|
| 204 |
+
palette: List[PaletteColor] = []
|
| 205 |
+
for new_i, idx in enumerate(np.argsort(-props)):
|
| 206 |
+
r, g, b = int(centers_rgb[idx, 0]), int(centers_rgb[idx, 1]), int(centers_rgb[idx, 2])
|
| 207 |
+
palette.append(PaletteColor(new_i, (r, g, b), f"#{r:02X}{g:02X}{b:02X}", round(float(props[idx]), 4), solve_tube_recipe((r, g, b))))
|
| 208 |
+
return palette
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def auto_crop_borders(img_rgb: np.ndarray, tol: int = 18, max_crop_ratio: float = 0.15) -> np.ndarray:
|
| 212 |
+
h, w = img_rgb.shape[:2]
|
| 213 |
+
gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
|
| 214 |
+
is_br = (gray.std(axis=1) < 8.0) & ((gray.mean(axis=1) > 255 - tol) | (gray.mean(axis=1) < tol))
|
| 215 |
+
is_bc = (gray.std(axis=0) < 8.0) & ((gray.mean(axis=0) > 255 - tol) | (gray.mean(axis=0) < tol))
|
| 216 |
+
top, bottom, left, right = 0, h, 0, w
|
| 217 |
+
while top < int(h * max_crop_ratio) and is_br[top]:
|
| 218 |
+
top += 1
|
| 219 |
+
while bottom > h - int(h * max_crop_ratio) and is_br[bottom - 1]:
|
| 220 |
+
bottom -= 1
|
| 221 |
+
while left < int(w * max_crop_ratio) and is_bc[left]:
|
| 222 |
+
left += 1
|
| 223 |
+
while right > w - int(w * max_crop_ratio) and is_bc[right - 1]:
|
| 224 |
+
right -= 1
|
| 225 |
+
if bottom - top < h * 0.6 or right - left < w * 0.6:
|
| 226 |
+
return img_rgb
|
| 227 |
+
return img_rgb[top:bottom, left:right]
|
| 228 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
|
| 230 |
+
def add_proportion_grid(img_rgb: np.ndarray, grid_n: int = 4) -> np.ndarray:
|
| 231 |
+
out = img_rgb.copy()
|
| 232 |
+
h, w = out.shape[:2]
|
| 233 |
+
for i in range(1, grid_n):
|
| 234 |
+
cv2.line(out, (0, int(round(h * i / grid_n))), (w, int(round(h * i / grid_n))), (160, 185, 220), 1, cv2.LINE_AA)
|
| 235 |
+
cv2.line(out, (int(round(w * i / grid_n)), 0), (int(round(w * i / grid_n)), h), (160, 185, 220), 1, cv2.LINE_AA)
|
| 236 |
+
return out
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def render_palette_card(palette: List[PaletteColor]) -> np.ndarray:
|
| 240 |
+
card_w, row_h = 740, 52
|
| 241 |
+
im = Image.new("RGB", (card_w, 44 + len(palette) * row_h), (249, 247, 243))
|
| 242 |
+
draw = ImageDraw.Draw(im)
|
| 243 |
+
draw.text((16, 12), "Your Simple Physical Palette & Tube Mixing Guide (Kubelka-Munk)", fill=(30, 30, 30))
|
| 244 |
+
for i, c in enumerate(palette):
|
| 245 |
+
y0 = 40 + i * row_h
|
| 246 |
+
draw.rectangle([16, y0 + 5, 82, y0 + row_h - 5], fill=c.rgb, outline=(60, 60, 60), width=1)
|
| 247 |
+
recipe_str = " + ".join(f"{pct}% {name}" for name, pct in c.mixing_recipe)
|
| 248 |
+
draw.text((96, y0 + 6), f"Color #{c.index + 1} {c.hex} ({c.proportion * 100:.1f}%)", fill=(25, 25, 25))
|
| 249 |
+
draw.text((96, y0 + 26), f"Mix: {recipe_str}", fill=(75, 75, 75))
|
| 250 |
+
return np.array(im)
|
| 251 |
|
| 252 |
|
| 253 |
+
# ============================================================
|
| 254 |
+
# 3. Model Loading & Gradio UI
|
| 255 |
+
# ============================================================
|
| 256 |
+
HERE = Path(__file__).resolve().parent
|
| 257 |
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 258 |
MODEL = None
|
| 259 |
+
MODEL_STATUS = "Model not loaded"
|
| 260 |
|
| 261 |
|
| 262 |
def load_paintpath_model(model_dir: str = "", ckpt_path: str = "", hf_repo: str = ""):
|
| 263 |
global MODEL, MODEL_STATUS
|
| 264 |
+
token = os.environ.get("HF_TOKEN") or None
|
| 265 |
|
| 266 |
+
if model_dir and Path(model_dir).exists() and (Path(model_dir) / "config.json").exists():
|
| 267 |
+
MODEL = PaintPathNet.from_pretrained(model_dir, pretrained=False).to(DEVICE).eval()
|
| 268 |
+
MODEL_STATUS = f"Loaded local HF model: {model_dir} ({DEVICE})"
|
|
|
|
|
|
|
| 269 |
return
|
| 270 |
|
|
|
|
| 271 |
if hf_repo:
|
| 272 |
+
MODEL = PaintPathNet.from_pretrained(hf_repo, pretrained=False, token=token).to(DEVICE).eval()
|
| 273 |
+
MODEL_STATUS = f"Loaded HF Hub model: {hf_repo} ({DEVICE})"
|
|
|
|
| 274 |
return
|
| 275 |
|
|
|
|
| 276 |
if ckpt_path and Path(ckpt_path).exists():
|
| 277 |
m = PaintPathNet(pretrained=False).to(DEVICE)
|
| 278 |
ckpt = torch.load(ckpt_path, map_location=DEVICE)
|
| 279 |
m.load_state_dict(ckpt["model"] if "model" in ckpt else ckpt)
|
| 280 |
+
MODEL = m.eval()
|
|
|
|
| 281 |
MODEL_STATUS = f"Loaded checkpoint: {ckpt_path} ({DEVICE})"
|
| 282 |
return
|
| 283 |
|
| 284 |
MODEL = None
|
| 285 |
+
MODEL_STATUS = "⚠️ Set HF_MODEL_REPO in Space Settings (Variables) to load your trained PaintPathNet!"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
|
| 288 |
@torch.no_grad()
|
| 289 |
def predict_roadmap(input_img: np.ndarray, num_colors: int, show_grid: bool, inference_size: int):
|
| 290 |
if input_img is None:
|
| 291 |
return None, None, None, None, None, "لطفاً یک تصویر نقاشی آپلود کنید."
|
| 292 |
+
if MODEL is None:
|
| 293 |
+
return None, None, None, None, None, MODEL_STATUS
|
| 294 |
|
| 295 |
clean = auto_crop_borders(input_img)
|
| 296 |
h, w = clean.shape[:2]
|
|
|
|
| 297 |
scale = inference_size / max(h, w)
|
| 298 |
nw = max(64, (int(round(w * scale)) // 32) * 32)
|
| 299 |
nh = max(64, (int(round(h * scale)) // 32) * 32)
|
|
|
|
| 302 |
palette = extract_physical_palette(resized, k=int(num_colors))
|
| 303 |
pal_card = render_palette_card(palette)
|
| 304 |
|
| 305 |
+
inp = torch.from_numpy(resized).permute(2, 0, 1).unsqueeze(0).float().to(DEVICE) / 255.0
|
| 306 |
+
gpu_name = torch.cuda.get_device_name(0) if DEVICE.type == "cuda" else ""
|
| 307 |
+
use_amp = (DEVICE.type == "cuda") and ("1650" not in gpu_name and "1660" not in gpu_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
|
| 309 |
+
stages_out = []
|
| 310 |
+
for s_idx in range(4):
|
| 311 |
+
st = torch.tensor([s_idx], dtype=torch.long, device=DEVICE)
|
| 312 |
+
with torch.amp.autocast("cuda", enabled=use_amp, dtype=torch.float16):
|
| 313 |
+
pred = MODEL(inp, st)
|
| 314 |
+
arr = (pred[0].float().clamp(0, 1).permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8)
|
| 315 |
+
stages_out.append(arr)
|
| 316 |
+
|
| 317 |
+
s1, s2, s3, s4 = stages_out
|
| 318 |
if show_grid:
|
| 319 |
s1 = add_proportion_grid(s1, grid_n=4)
|
| 320 |
|
|
|
|
| 328 |
# 🎨 PaintPath — AI Teaches Humans to Paint
|
| 329 |
*«همیشه انسان کار را برای هوش مصنوعی ساده میکند؛ این بار هوش مصنوعی هنر را برای انسان ساده میکند تا نقاش بشود!»*
|
| 330 |
|
| 331 |
+
Upload any painting and **PaintPathNet** breaks it down into **4 beginner-friendly stages** + a **physical pigment mixing palette**.
|
| 332 |
"""
|
| 333 |
)
|
| 334 |
|
| 335 |
with gr.Row():
|
| 336 |
with gr.Column(scale=1):
|
| 337 |
+
in_img = gr.Image(type="numpy", label="Upload Painting / نقاشی را آپلود کن")
|
| 338 |
+
num_colors = gr.Slider(6, 12, value=8, step=1, label="Palette Colors / تعداد رنگ پالت")
|
| 339 |
+
show_grid = gr.Checkbox(value=True, label="Show 4×4 Proportion Grid on Stage 1")
|
| 340 |
+
inf_size = gr.Slider(256, 640, value=384, step=64, label="Output Size (px)")
|
| 341 |
+
run_btn = gr.Button("✨ Generate Amateur Painting Roadmap", variant="primary")
|
| 342 |
+
status = gr.Textbox(label="Model Status", value=MODEL_STATUS, interactive=False)
|
| 343 |
with gr.Column(scale=1):
|
| 344 |
+
pal_out = gr.Image(label="🎨 Physical Artist Palette & Tube Mixing Recipes")
|
| 345 |
|
| 346 |
+
gr.Markdown("### 🗺️ 4-Stage Progressive Painting Roadmap")
|
| 347 |
with gr.Row():
|
| 348 |
+
s1_out = gr.Image(label="Stage 1: Pencil Sketch & Proportions")
|
| 349 |
+
s2_out = gr.Image(label="Stage 2: Broad Color Blocking (Wide Brush)")
|
| 350 |
+
s3_out = gr.Image(label="Stage 3: Shadows & Value Structure")
|
| 351 |
+
s4_out = gr.Image(label="Stage 4: Mid-Details & Brushwork")
|
| 352 |
|
| 353 |
run_btn.click(
|
| 354 |
fn=predict_roadmap,
|
|
|
|
| 358 |
return demo
|
| 359 |
|
| 360 |
|
| 361 |
+
if os.environ.get("SPACE_ID"):
|
| 362 |
+
load_paintpath_model(
|
| 363 |
+
model_dir=str(HERE / "hf_model"),
|
| 364 |
+
hf_repo=os.environ.get("HF_MODEL_REPO", ""),
|
| 365 |
+
)
|
| 366 |
+
demo = build_ui()
|
| 367 |
+
demo.launch()
|
| 368 |
+
elif __name__ == "__main__":
|
| 369 |
parser = argparse.ArgumentParser()
|
| 370 |
parser.add_argument("--model-dir", type=str, default=str(HERE / "hf_model"))
|
| 371 |
parser.add_argument("--ckpt", type=str, default="")
|
|
|
|
| 376 |
load_paintpath_model(args.model_dir, args.ckpt, args.hf_repo)
|
| 377 |
demo = build_ui()
|
| 378 |
demo.launch(server_name="127.0.0.1", server_port=args.port, inbrowser=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|