Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
"""
|
| 2 |
-
hf_space/app.py — PaintPath Studio v2 by Ali Jahani
|
| 3 |
100% Self-Contained Hugging Face Space & Local Runner.
|
| 4 |
|
| 5 |
-
Model : https://huggingface.co/tarfandoon/paintpath-net
|
| 6 |
Author : Ali Jahani
|
| 7 |
Website : https://jahaniwww.com
|
| 8 |
Telegram: https://t.me/tarfandoonchannel
|
|
@@ -40,7 +40,7 @@ except ImportError:
|
|
| 40 |
|
| 41 |
|
| 42 |
# ============================================================
|
| 43 |
-
# 1.
|
| 44 |
# ============================================================
|
| 45 |
class FiLMResBlock(nn.Module):
|
| 46 |
def __init__(self, in_ch: int, out_ch: int, cond_dim: int):
|
|
@@ -63,12 +63,12 @@ class FiLMResBlock(nn.Module):
|
|
| 63 |
return F.gelu(h + self.skip(x))
|
| 64 |
|
| 65 |
|
| 66 |
-
class
|
| 67 |
def __init__(
|
| 68 |
self,
|
| 69 |
backbone: str = "convnext_small.fb_in22k_ft_in1k",
|
| 70 |
pretrained: bool = False,
|
| 71 |
-
num_stages: int =
|
| 72 |
cond_dim: int = 256,
|
| 73 |
):
|
| 74 |
super().__init__()
|
|
@@ -91,6 +91,17 @@ class PaintPathNet(nn.Module, PyTorchModelHubMixin):
|
|
| 91 |
nn.Linear(cond_dim, cond_dim),
|
| 92 |
)
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
self.bottleneck = FiLMResBlock(chs[3], 512, cond_dim)
|
| 95 |
self.dec3 = FiLMResBlock(512 + chs[2], 256, cond_dim)
|
| 96 |
self.dec2 = FiLMResBlock(256 + chs[1], 128, cond_dim)
|
|
@@ -109,7 +120,6 @@ class PaintPathNet(nn.Module, PyTorchModelHubMixin):
|
|
| 109 |
self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
|
| 110 |
|
| 111 |
def extract_focal_map(self, img: torch.Tensor) -> torch.Tensor:
|
| 112 |
-
"""Deep visual eye-attention saliency map directly from ConvNeXt f3 & f4."""
|
| 113 |
x_norm = (img - self.mean) / self.std
|
| 114 |
_, _, f3, f4 = self.encoder(x_norm)
|
| 115 |
m4 = torch.norm(f4, dim=1, keepdim=True)
|
|
@@ -122,10 +132,11 @@ class PaintPathNet(nn.Module, PyTorchModelHubMixin):
|
|
| 122 |
m = (m - m.amin(dim=(-2, -1), keepdim=True)) / (m.amax(dim=(-2, -1), keepdim=True) - m.amin(dim=(-2, -1), keepdim=True) + 1e-6)
|
| 123 |
return m
|
| 124 |
|
| 125 |
-
def forward(self, img: torch.Tensor, stage_idx: torch.Tensor)
|
| 126 |
x_norm = (img - self.mean) / self.std
|
| 127 |
f1, f2, f3, f4 = self.encoder(x_norm)
|
| 128 |
cond = self.stage_emb(stage_idx)
|
|
|
|
| 129 |
|
| 130 |
h = self.bottleneck(f4, cond)
|
| 131 |
h = F.interpolate(h, size=f3.shape[-2:], mode="bilinear", align_corners=False)
|
|
@@ -143,11 +154,11 @@ class PaintPathNet(nn.Module, PyTorchModelHubMixin):
|
|
| 143 |
|
| 144 |
h = F.interpolate(h, size=(H, W), mode="bilinear", align_corners=False)
|
| 145 |
h = self.up_full(torch.cat([h, img], dim=1), cond)
|
| 146 |
-
return self.out_head(h)
|
| 147 |
|
| 148 |
|
| 149 |
# ============================================================
|
| 150 |
-
# 2. Physical Pigment Mixing,
|
| 151 |
# ============================================================
|
| 152 |
ARTIST_TUBES: Dict[str, Tuple[int, int, int]] = {
|
| 153 |
"Titanium White": (245, 245, 242),
|
|
@@ -260,86 +271,113 @@ def auto_crop_borders(img_rgb: np.ndarray, tol: int = 18, max_crop_ratio: float
|
|
| 260 |
return img_rgb[top:bottom, left:right]
|
| 261 |
|
| 262 |
|
| 263 |
-
def
|
| 264 |
-
out = img_rgb.copy()
|
| 265 |
-
h, w = out.shape[:2]
|
| 266 |
-
for i in range(1, grid_n):
|
| 267 |
-
cv2.line(out, (0, int(round(h * i / grid_n))), (w, int(round(h * i / grid_n))), (110, 160, 230), 1, cv2.LINE_AA)
|
| 268 |
-
cv2.line(out, (int(round(w * i / grid_n)), 0), (int(round(w * i / grid_n)), h), (110, 160, 230), 1, cv2.LINE_AA)
|
| 269 |
-
return out
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
def make_rough_shapes_sketch(sketch_rgb: np.ndarray, show_grid: bool = True) -> np.ndarray:
|
| 273 |
-
"""Stage 1: Only the boldest structural outlines (removes small details so beginner gets proportions first)."""
|
| 274 |
-
gray = cv2.cvtColor(sketch_rgb, cv2.COLOR_RGB2GRAY)
|
| 275 |
-
inv = (gray < 195).astype(np.uint8) * 255
|
| 276 |
-
contours, _ = cv2.findContours(inv, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
|
| 277 |
-
# Keep only the top longest structural contours
|
| 278 |
-
contours = sorted(contours, key=lambda c: cv2.arcLength(c, False), reverse=True)
|
| 279 |
-
keep = max(12, int(len(contours) * 0.22))
|
| 280 |
-
canvas = np.full(sketch_rgb.shape, 252, dtype=np.uint8)
|
| 281 |
-
cv2.drawContours(canvas, contours[:keep], -1, (45, 50, 65), 1, cv2.LINE_AA)
|
| 282 |
-
if show_grid:
|
| 283 |
-
canvas = add_proportion_grid(canvas, 4)
|
| 284 |
-
return canvas
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
def make_sepia_underpainting(stage2_rgb: np.ndarray) -> np.ndarray:
|
| 288 |
-
"""Stage 3: Classical warm Burnt Umber monochrome tonal wash (Imprimatura / Grisaille)."""
|
| 289 |
-
gray = cv2.cvtColor(stage2_rgb, cv2.COLOR_RGB2GRAY).astype(np.float32) / 255.0
|
| 290 |
-
# Blend between dark Burnt Umber (78, 48, 30) and warm cream canvas (248, 240, 224)
|
| 291 |
-
dark = np.array([72, 44, 28], dtype=np.float32)
|
| 292 |
-
light = np.array([248, 241, 226], dtype=np.float32)
|
| 293 |
-
wash = dark[None, None, :] * (1.0 - gray[..., None]) + light[None, None, :] * gray[..., None]
|
| 294 |
-
return np.clip(wash, 0, 255).astype(np.uint8)
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
def make_sketch_animation_gif(sketch_rgb: np.ndarray, show_grid: bool = True) -> str:
|
| 298 |
"""
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
main structural shapes -> medium forms -> fine details, and draws them progressively!
|
| 302 |
"""
|
| 303 |
-
h, w = sketch_rgb.shape[:2]
|
| 304 |
gray = cv2.cvtColor(sketch_rgb, cv2.COLOR_RGB2GRAY)
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
base = add_proportion_grid(base, 4)
|
| 312 |
|
| 313 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
frames: List[Image.Image] = []
|
| 315 |
durations: List[int] = []
|
| 316 |
bar_h = 30
|
| 317 |
|
| 318 |
-
def
|
| 319 |
-
|
| 320 |
-
|
|
|
|
|
|
|
| 321 |
d = ImageDraw.Draw(out)
|
| 322 |
-
d.text((10, 7), f"
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
d.rectangle([10, bar_h - 5,
|
| 326 |
-
d.rectangle([10, bar_h - 5, 10 + bar_w, bar_h - 2], fill=(217, 119, 6))
|
| 327 |
return out
|
| 328 |
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
canvas = base.copy()
|
| 336 |
-
cv2.drawContours(canvas, contours[:k], -1, (38, 40, 48), 1, cv2.LINE_AA)
|
| 337 |
-
frames.append(_frame_with_bar(canvas, int(round(f * 100 / n_frames))))
|
| 338 |
durations.append(160)
|
| 339 |
|
| 340 |
-
#
|
| 341 |
-
|
| 342 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
durations.append(2200)
|
| 344 |
|
| 345 |
tmp = tempfile.NamedTemporaryFile(suffix=".gif", delete=False)
|
|
@@ -349,40 +387,41 @@ def make_sketch_animation_gif(sketch_rgb: np.ndarray, show_grid: bool = True) ->
|
|
| 349 |
|
| 350 |
|
| 351 |
def make_timelapse_gif(stages_7: List[np.ndarray]) -> str:
|
| 352 |
-
"""
|
| 353 |
labels = [
|
| 354 |
-
"1/7:
|
| 355 |
-
"2/7: Full Pencil Sketch",
|
| 356 |
-
"3/7:
|
| 357 |
-
"4/7: Broad Color Blocking",
|
| 358 |
-
"5/7: Shadows & 3D Volume",
|
| 359 |
-
"6/7: Mid-Details & Brushwork",
|
| 360 |
-
"7/7: Final Highlights",
|
| 361 |
]
|
| 362 |
h, w = stages_7[0].shape[:2]
|
| 363 |
bar_h = 32
|
| 364 |
|
| 365 |
-
def _annotate(arr: np.ndarray, text: str,
|
| 366 |
-
canvas = Image.new("RGB", (w, h + bar_h), (245,
|
| 367 |
canvas.paste(Image.fromarray(arr), (0, bar_h))
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
prog = int((w - 20) *
|
| 371 |
-
|
| 372 |
-
|
| 373 |
return canvas
|
| 374 |
|
| 375 |
frames: List[Image.Image] = []
|
| 376 |
durations: List[int] = []
|
|
|
|
| 377 |
for i, img in enumerate(stages_7):
|
| 378 |
-
frames.append(_annotate(img, labels[i], i))
|
| 379 |
-
durations.append(
|
| 380 |
-
if i <
|
| 381 |
nxt = stages_7[i + 1]
|
| 382 |
-
for alpha in (0.
|
| 383 |
blend = cv2.addWeighted(img, 1.0 - alpha, nxt, alpha, 0)
|
| 384 |
-
frames.append(_annotate(blend, labels[i + 1], i + 1))
|
| 385 |
-
durations.append(
|
| 386 |
|
| 387 |
tmp = tempfile.NamedTemporaryFile(suffix=".gif", delete=False)
|
| 388 |
tmp.close()
|
|
@@ -391,7 +430,6 @@ def make_timelapse_gif(stages_7: List[np.ndarray]) -> str:
|
|
| 391 |
|
| 392 |
|
| 393 |
def make_clear_paint_zones(prev_img: np.ndarray, curr_img: np.ndarray) -> np.ndarray:
|
| 394 |
-
"""Clearly highlight WHERE to paint in this step with crisp warm-amber contours + active color."""
|
| 395 |
diff = np.mean(np.abs(curr_img.astype(np.float32) - prev_img.astype(np.float32)), axis=-1)
|
| 396 |
diff = cv2.GaussianBlur(diff, (7, 7), 0)
|
| 397 |
thr = max(9.0, float(np.percentile(diff, 68)))
|
|
@@ -399,10 +437,8 @@ def make_clear_paint_zones(prev_img: np.ndarray, curr_img: np.ndarray) -> np.nda
|
|
| 399 |
bin_mask = cv2.morphologyEx(bin_mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
|
| 400 |
|
| 401 |
soft = cv2.GaussianBlur(bin_mask.astype(np.float32) / 255.0, (9, 9), 0)[..., None]
|
| 402 |
-
gray_bg = cv2.cvtColor(cv2.cvtColor(curr_img, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB).astype(np.float32) * 0.35 +
|
| 403 |
blended = np.ascontiguousarray(np.clip(gray_bg * (1.0 - soft) + curr_img.astype(np.float32) * soft, 0, 255).astype(np.uint8))
|
| 404 |
-
|
| 405 |
-
# Draw crisp orange/magenta contour outlines around active zones
|
| 406 |
contours, _ = cv2.findContours(bin_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 407 |
cv2.drawContours(blended, contours, -1, (234, 88, 12), 2, cv2.LINE_AA)
|
| 408 |
return blended
|
|
@@ -426,8 +462,38 @@ def make_attention_overlay(img_rgb: np.ndarray, focal_01: np.ndarray) -> np.ndar
|
|
| 426 |
return cv2.addWeighted(img_rgb, 0.50, heat_rgb, 0.50, 0)
|
| 427 |
|
| 428 |
|
| 429 |
-
def
|
| 430 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
img_lab = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2LAB).astype(np.float32)
|
| 432 |
t_lab = cv2.cvtColor(np.array([[target_rgb]], dtype=np.uint8), cv2.COLOR_RGB2LAB).astype(np.float32)[0, 0]
|
| 433 |
dist = np.linalg.norm(img_lab - t_lab[None, None, :], axis=-1)
|
|
@@ -436,7 +502,7 @@ def highlight_target_rgb_on_canvas(img_rgb: np.ndarray, target_rgb: Tuple[int, i
|
|
| 436 |
mask_u8 = (mask > 0.45).astype(np.uint8) * 255
|
| 437 |
soft = cv2.GaussianBlur(mask.astype(np.float32), (7, 7), 0)[..., None]
|
| 438 |
|
| 439 |
-
bg = cv2.cvtColor(cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB).astype(np.float32) * 0.
|
| 440 |
out = np.ascontiguousarray(np.clip(bg * (1.0 - soft) + img_rgb.astype(np.float32) * soft, 0, 255).astype(np.uint8))
|
| 441 |
contours, _ = cv2.findContours(mask_u8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 442 |
cv2.drawContours(out, contours, -1, (220, 38, 38), 1, cv2.LINE_AA)
|
|
@@ -451,12 +517,12 @@ def highlight_target_rgb_on_canvas(img_rgb: np.ndarray, target_rgb: Tuple[int, i
|
|
| 451 |
fa_name = TUBE_PERSIAN.get(name, name)
|
| 452 |
bars_html += f"""
|
| 453 |
<div style="margin: 8px 0;">
|
| 454 |
-
<div style="display:flex; justify-content:space-between; font-size:13px; color:#1f2937 !important; font-weight:
|
| 455 |
<span>🎨 {fa_name} ({name})</span>
|
| 456 |
<span>{pct}%</span>
|
| 457 |
</div>
|
| 458 |
<div style="background:#e5e7eb; border-radius:8px; height:12px; overflow:hidden; margin-top:3px;">
|
| 459 |
-
<div style="width:{pct}%; height:100%; background:rgb({tr},{tg},{tb}); border:1px solid rgba(0,0,0,0.
|
| 460 |
</div>
|
| 461 |
</div>
|
| 462 |
"""
|
|
@@ -467,10 +533,10 @@ def highlight_target_rgb_on_canvas(img_rgb: np.ndarray, target_rgb: Tuple[int, i
|
|
| 467 |
<div style="width:56px; height:56px; border-radius:12px; background:{hex_code}; border:2px solid #374151; flex-shrink:0;"></div>
|
| 468 |
<div>
|
| 469 |
<div style="font-size:16px; font-weight:800; color:#111827 !important;">رنگ انتخابشده: <code>{hex_code}</code></div>
|
| 470 |
-
<div style="font-size:13px; color:#4b5563 !important;">RGB({r}, {g}, {b}) —
|
| 471 |
</div>
|
| 472 |
</div>
|
| 473 |
-
<div style="font-size:14px; font-weight:700; color:#111827 !important; margin-bottom:6px;">🧪 دستور ترکیب واقعی رنگهای تیوپی (
|
| 474 |
{bars_html}
|
| 475 |
</div>
|
| 476 |
"""
|
|
@@ -515,25 +581,24 @@ def evaluate_amateur_painting(ref_img: np.ndarray, user_img: np.ndarray) -> Tupl
|
|
| 515 |
struct_score = float(np.clip((corr + 0.2) * 85.0, 0, 100))
|
| 516 |
|
| 517 |
overall = 0.40 * color_score + 0.35 * value_score + 0.25 * struct_score
|
| 518 |
-
|
| 519 |
err_blur = cv2.GaussianBlur((np.clip(delta_e / 55.0, 0, 1) * 255).astype(np.uint8), (15, 15), 0)
|
| 520 |
heat = cv2.cvtColor(cv2.applyColorMap(err_blur, cv2.COLORMAP_JET), cv2.COLOR_BGR2RGB)
|
| 521 |
overlay = cv2.addWeighted(usr, 0.58, heat, 0.42, 0)
|
| 522 |
|
| 523 |
tips = []
|
| 524 |
if val_diff > 10:
|
| 525 |
-
tips.append("- **سایهها کمی
|
| 526 |
elif val_diff < -10:
|
| 527 |
tips.append("- **نقاشی کمی تیره شده:** در بخشهای روشن کمی سفید تیتانیوم اضافه کن.")
|
| 528 |
else:
|
| 529 |
tips.append("- **تعادل نور و سایه عالی است!**")
|
| 530 |
if color_score < 65:
|
| 531 |
-
tips.append("- **دقت رنگ:** در تب «
|
| 532 |
if struct_score < 55:
|
| 533 |
-
tips.append("- **تناسبات:** با انیمی
|
| 534 |
|
| 535 |
report = (
|
| 536 |
-
f"### 🏆 امتیاز کلی
|
| 537 |
f"- دقت رنگها: `{color_score:.1f}` | تعادل نور و سایه: `{value_score:.1f}` | تناسبات: `{struct_score:.1f}`\n\n"
|
| 538 |
f"#### 💡 توصیههای مربی (قرمز = نیاز به اصلاح، آبی = عالی):\n" + "\n".join(tips)
|
| 539 |
)
|
|
@@ -544,19 +609,44 @@ def evaluate_amateur_painting(ref_img: np.ndarray, user_img: np.ndarray) -> Tupl
|
|
| 544 |
# 3. 7-Step Pedagogical Curriculum & Model Loading
|
| 545 |
# ============================================================
|
| 546 |
HERE = Path(__file__).resolve().parent
|
| 547 |
-
DEFAULT_HF_REPO = "tarfandoon/paintpath-net"
|
| 548 |
ON_SPACES = bool(os.environ.get("SPACE_ID"))
|
| 549 |
MODEL = None
|
| 550 |
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 560 |
|
| 561 |
|
| 562 |
def load_paintpath_model(model_dir: str = "", ckpt_path: str = "", hf_repo: str = ""):
|
|
@@ -565,16 +655,16 @@ def load_paintpath_model(model_dir: str = "", ckpt_path: str = "", hf_repo: str
|
|
| 565 |
init_dev = torch.device("cpu") if ON_SPACES else torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 566 |
|
| 567 |
if model_dir and Path(model_dir).exists() and (Path(model_dir) / "config.json").exists():
|
| 568 |
-
MODEL =
|
| 569 |
return
|
| 570 |
|
| 571 |
repo = hf_repo or DEFAULT_HF_REPO
|
| 572 |
if repo:
|
| 573 |
-
MODEL =
|
| 574 |
return
|
| 575 |
|
| 576 |
if ckpt_path and Path(ckpt_path).exists():
|
| 577 |
-
m =
|
| 578 |
ckpt = torch.load(ckpt_path, map_location=init_dev)
|
| 579 |
m.load_state_dict(ckpt["model"] if "model" in ckpt else ckpt)
|
| 580 |
MODEL = m.eval()
|
|
@@ -588,16 +678,16 @@ def _gpu_decorator(fn):
|
|
| 588 |
|
| 589 |
@_gpu_decorator
|
| 590 |
@torch.no_grad()
|
| 591 |
-
def run_paintpath_studio(input_img: np.ndarray,
|
| 592 |
if input_img is None or MODEL is None:
|
| 593 |
-
return None, None, None, None, "لطفاً ابتدا یک نقاشی آپلود کن.", 1, None, None, None, "", gr.update(), None, None
|
| 594 |
|
| 595 |
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 596 |
MODEL.to(dev)
|
| 597 |
|
| 598 |
clean = auto_crop_borders(input_img)
|
| 599 |
h, w = clean.shape[:2]
|
| 600 |
-
scale =
|
| 601 |
nw = max(64, (int(round(w * scale)) // 32) * 32)
|
| 602 |
nh = max(64, (int(round(h * scale)) // 32) * 32)
|
| 603 |
resized = cv2.resize(clean, (nw, nh), interpolation=cv2.INTER_AREA)
|
|
@@ -606,43 +696,60 @@ def run_paintpath_studio(input_img: np.ndarray, num_colors: int, show_grid: bool
|
|
| 606 |
gpu_name = torch.cuda.get_device_name(0) if dev.type == "cuda" else ""
|
| 607 |
use_amp = (dev.type == "cuda") and ("1650" not in gpu_name and "1660" not in gpu_name)
|
| 608 |
|
| 609 |
-
|
|
|
|
|
|
|
| 610 |
with torch.amp.autocast("cuda", enabled=use_amp, dtype=torch.float16):
|
| 611 |
focal_t = MODEL.extract_focal_map(inp)
|
| 612 |
-
for s_idx in range(
|
| 613 |
st = torch.tensor([s_idx], dtype=torch.long, device=dev)
|
| 614 |
-
pred = MODEL(inp, st)
|
|
|
|
|
|
|
| 615 |
arr = np.ascontiguousarray((pred[0].float().clamp(0, 1).permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8))
|
| 616 |
-
|
| 617 |
|
| 618 |
focal_01 = focal_t[0, 0].float().cpu().numpy()
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
|
|
|
|
|
|
|
|
|
| 635 |
blank = np.full_like(resized, 248)
|
| 636 |
paint_zones = {
|
| 637 |
-
1:
|
| 638 |
-
2:
|
| 639 |
-
3: make_clear_paint_zones(blank,
|
| 640 |
-
4: make_clear_paint_zones(
|
| 641 |
-
5: make_clear_paint_zones(
|
| 642 |
-
6: make_clear_paint_zones(
|
| 643 |
-
7: make_clear_paint_zones(
|
| 644 |
}
|
| 645 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 646 |
palette = extract_physical_palette(resized, k=int(num_colors))
|
| 647 |
pal_card = render_palette_card(palette)
|
| 648 |
loc_img, loc_html = highlight_target_rgb_on_canvas(resized, palette[0].rgb)
|
|
@@ -655,16 +762,19 @@ def run_paintpath_studio(input_img: np.ndarray, num_colors: int, show_grid: bool
|
|
| 655 |
"resized": resized,
|
| 656 |
"step_imgs": step_imgs,
|
| 657 |
"paint_zones": paint_zones,
|
|
|
|
| 658 |
"palette": palette,
|
| 659 |
}
|
| 660 |
|
| 661 |
return (
|
| 662 |
state,
|
|
|
|
| 663 |
sketch_gif,
|
| 664 |
timelapse_gif,
|
| 665 |
step_imgs[1],
|
| 666 |
-
|
| 667 |
1,
|
|
|
|
| 668 |
resized,
|
| 669 |
pal_card,
|
| 670 |
loc_img,
|
|
@@ -680,7 +790,7 @@ def render_slide(step_num: int, show_zones: bool, state: Optional[dict]):
|
|
| 680 |
return None, "ابتدا یک نقاشی آپلود کن.", 1
|
| 681 |
s = max(1, min(7, int(step_num)))
|
| 682 |
img = state["paint_zones"][s] if show_zones else state["step_imgs"][s]
|
| 683 |
-
return img,
|
| 684 |
|
| 685 |
|
| 686 |
def prev_slide(step_num: int, show_zones: bool, state: Optional[dict]):
|
|
@@ -703,42 +813,39 @@ def on_color_dropdown(color_label: str, state: Optional[dict]):
|
|
| 703 |
|
| 704 |
|
| 705 |
def on_canvas_click(state: Optional[dict], evt: gr.SelectData):
|
| 706 |
-
"""Interactive Eyedropper: Click ANY pixel on the painting to extract & mix its exact paint recipe!"""
|
| 707 |
if not state:
|
| 708 |
return None, "<p>ابتدا نقاشی را تحلیل کن.</p>"
|
| 709 |
img = state["resized"]
|
| 710 |
x, y = int(evt.index[0]), int(evt.index[1])
|
| 711 |
h, w = img.shape[:2]
|
| 712 |
-
x = max(0, min(x, w - 1))
|
| 713 |
-
y = max(0, min(y, h - 1))
|
| 714 |
-
# Average a tiny 5x5 patch around click so single-pixel noise doesn't skew color
|
| 715 |
patch = img[max(0, y - 2) : min(h, y + 3), max(0, x - 2) : min(w, x + 3)]
|
| 716 |
mean_rgb = tuple(int(round(v)) for v in patch.reshape(-1, 3).mean(axis=0))
|
| 717 |
return highlight_target_rgb_on_canvas(img, mean_rgb, tolerance=24.0)
|
| 718 |
|
| 719 |
|
| 720 |
# ============================================================
|
| 721 |
-
# 4. Crisp, High-Contrast
|
| 722 |
# ============================================================
|
| 723 |
CUSTOM_CSS = """
|
| 724 |
.studio-hero {
|
| 725 |
-
background: linear-gradient(135deg, #
|
| 726 |
-
border: 2px solid #
|
| 727 |
-
border-radius:
|
| 728 |
-
padding:
|
| 729 |
margin-bottom: 18px !important;
|
| 730 |
text-align: center !important;
|
| 731 |
-
box-shadow: 0
|
| 732 |
}
|
| 733 |
.studio-hero h1 {
|
| 734 |
margin: 0 0 8px 0 !important;
|
| 735 |
-
font-size: 2.
|
| 736 |
font-weight: 900 !important;
|
| 737 |
color: #111827 !important;
|
| 738 |
}
|
| 739 |
.studio-hero p {
|
| 740 |
margin: 0 auto 16px auto !important;
|
| 741 |
-
max-width:
|
| 742 |
font-size: 1.04rem !important;
|
| 743 |
font-weight: 500 !important;
|
| 744 |
color: #374151 !important;
|
|
@@ -753,14 +860,13 @@ CUSTOM_CSS = """
|
|
| 753 |
display: inline-flex !important;
|
| 754 |
align-items: center !important;
|
| 755 |
gap: 6px !important;
|
| 756 |
-
padding:
|
| 757 |
border-radius: 999px !important;
|
| 758 |
background: #1f2937 !important;
|
| 759 |
color: #ffffff !important;
|
| 760 |
text-decoration: none !important;
|
| 761 |
font-size: 0.88rem !important;
|
| 762 |
font-weight: 700 !important;
|
| 763 |
-
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12) !important;
|
| 764 |
}
|
| 765 |
.brand-links a:hover {
|
| 766 |
background: #d97706 !important;
|
|
@@ -768,99 +874,103 @@ CUSTOM_CSS = """
|
|
| 768 |
}
|
| 769 |
.studio-footer {
|
| 770 |
text-align: center !important;
|
| 771 |
-
margin-top:
|
| 772 |
padding: 16px !important;
|
| 773 |
-
background: #
|
| 774 |
-
border: 1px solid #
|
| 775 |
border-radius: 14px !important;
|
| 776 |
color: #1f2937 !important;
|
| 777 |
-
font-size: 0.
|
| 778 |
font-weight: 600 !important;
|
| 779 |
}
|
| 780 |
.studio-footer a {
|
| 781 |
color: #b45309 !important;
|
| 782 |
text-decoration: none !important;
|
| 783 |
-
font-weight:
|
| 784 |
}
|
| 785 |
"""
|
| 786 |
|
| 787 |
|
| 788 |
def build_ui():
|
| 789 |
-
with gr.Blocks(title="PaintPath Studio — Ali Jahani") as demo:
|
| 790 |
studio_state = gr.State(value=None)
|
| 791 |
|
| 792 |
gr.HTML(
|
| 793 |
"""
|
| 794 |
<div class="studio-hero">
|
| 795 |
-
<h1>🎨 PaintPath Studio —
|
| 796 |
-
<p>همیشه انسان کار را برای هوش مصنوعی ساده میکند؛ این بار هوش مصنوعی نقاشی را ب
|
| 797 |
<div class="brand-links">
|
| 798 |
<a href="https://jahaniwww.com" target="_blank">👤 Ali Jahani — jahaniwww.com</a>
|
| 799 |
<a href="https://t.me/tarfandoonchannel" target="_blank">✈️ Telegram: @tarfandoonchannel</a>
|
| 800 |
-
<a href="https://huggingface.co/tarfandoon/paintpath-net" target="_blank">🤗 Model:
|
| 801 |
</div>
|
| 802 |
</div>
|
| 803 |
"""
|
| 804 |
)
|
| 805 |
|
| 806 |
-
# Clean Upload
|
| 807 |
with gr.Row(equal_height=True):
|
| 808 |
with gr.Column(scale=2):
|
| 809 |
in_img = gr.Image(type="numpy", label="۱. نقاشی مورد نظرت را اینجا آپلود کن", height=270)
|
| 810 |
with gr.Column(scale=1):
|
| 811 |
-
gr.Markdown("###
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
|
|
|
| 816 |
|
| 817 |
with gr.Tabs():
|
| 818 |
-
# TAB 1:
|
| 819 |
-
with gr.Tab("🎬 ۱.
|
| 820 |
with gr.Row():
|
| 821 |
with gr.Column(scale=1):
|
| 822 |
-
gr.Markdown("###
|
| 823 |
-
sketch_gif_out = gr.Image(label="تماشا کن چطور اول خطوط اصلی و بعد جزئیات کشیده میشود", interactive=False)
|
| 824 |
-
gr.Markdown("### 🎥 فیلم تایملپس کامل ۷ مرحلهای")
|
| 825 |
-
timelapse_out = gr.Image(label="سفر کامل از اسکچ تا اثر نهایی", interactive=False)
|
| 826 |
-
|
| 827 |
-
with gr.Column(scale=1):
|
| 828 |
-
gr.Markdown("### 🖼️ اسلاید تعاملی ۷ مرحلهای (همراه با نقاشی تو)")
|
| 829 |
slide_img = gr.Image(label="بوم هدف در مرحله فعلی", interactive=False)
|
| 830 |
with gr.Row():
|
| 831 |
prev_btn = gr.Button("⬅️ مرحله قبل")
|
| 832 |
next_btn = gr.Button("مرحله بعد ➡️", variant="primary")
|
| 833 |
with gr.Row():
|
| 834 |
-
step_slider = gr.Slider(1, 7, value=1, step=1, label="ا
|
| 835 |
-
zone_chk = gr.Checkbox(value=False, label="📍 نشان بده در این مرحله
|
| 836 |
-
slide_guide = gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 837 |
|
| 838 |
# TAB 2: Interactive Click-to-Extract Color Mixer & Canvas Locator
|
| 839 |
-
with gr.Tab("🎨 ۲.
|
| 840 |
-
gr.Markdown("### 💧 روی هر نقطهای از نقاشی سمت چپ کلیک کن تا
|
| 841 |
with gr.Row():
|
| 842 |
-
clickable_img = gr.Image(label="👆 روی هر نقطه نقاشی کلیک کن
|
| 843 |
color_loc_img = gr.Image(label="📍 تمام نقاطی که باید این رنگ را بزنی (کادر قرمز)", interactive=False)
|
| 844 |
with gr.Row():
|
| 845 |
with gr.Column(scale=1):
|
| 846 |
-
color_dropdown = gr.Dropdown(choices=[], label="یا از
|
| 847 |
-
color_recipe_html = gr.HTML("<div style='padding:12px; color:#4b5563;'>
|
| 848 |
with gr.Column(scale=1):
|
| 849 |
pal_out = gr.Image(label="کارت کامل پالت رنگ فیزیکی")
|
| 850 |
|
| 851 |
-
# TAB 3: Dedicated Eye Attention & Value Study
|
| 852 |
with gr.Tab("👁️ ۳. کانون توجه چ��م و نورپردازی"):
|
| 853 |
gr.Markdown(
|
| 854 |
-
"### 🔥
|
| 855 |
-
"
|
| 856 |
)
|
| 857 |
with gr.Row():
|
| 858 |
-
attn_out = gr.Image(label="🔥 نقشه کانون توجه چشم (
|
| 859 |
val_out = gr.Image(label="🌗 مطالعه ارزش نوری ۳ سطحی (تیره / میانی / روشن)")
|
| 860 |
|
| 861 |
# TAB 4: Check My Hand-Painted Canvas
|
| 862 |
with gr.Tab("🏆 ۴. ارزیابی نقاشیِ دستِ تو"):
|
| 863 |
-
gr.Markdown("از نقاشیای که خودت با دست روی بوم یا کاغذ کشیدی عکس بگیر و اینجا آپلود کن تا **امتیاز و نقشه اصلاح** بگیری!")
|
| 864 |
with gr.Row():
|
| 865 |
user_canvas_in = gr.Image(type="numpy", label="📸 عکس نقاشیِ دستِ خودت")
|
| 866 |
feedback_img_out = gr.Image(label="🔍 نقشه اصلاح (قرمز = نیاز به اصلاح، آبی = عالی)")
|
|
@@ -880,14 +990,16 @@ def build_ui():
|
|
| 880 |
# Events
|
| 881 |
run_btn.click(
|
| 882 |
fn=run_paintpath_studio,
|
| 883 |
-
inputs=[in_img,
|
| 884 |
outputs=[
|
| 885 |
studio_state,
|
|
|
|
| 886 |
sketch_gif_out,
|
| 887 |
timelapse_out,
|
| 888 |
slide_img,
|
| 889 |
slide_guide,
|
| 890 |
step_slider,
|
|
|
|
| 891 |
clickable_img,
|
| 892 |
pal_out,
|
| 893 |
color_loc_img,
|
|
@@ -898,41 +1010,13 @@ def build_ui():
|
|
| 898 |
],
|
| 899 |
)
|
| 900 |
|
| 901 |
-
step_slider.change(
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
)
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
inputs=[step_slider, zone_chk, studio_state],
|
| 909 |
-
outputs=[slide_img, slide_guide, step_slider],
|
| 910 |
-
)
|
| 911 |
-
prev_btn.click(
|
| 912 |
-
fn=prev_slide,
|
| 913 |
-
inputs=[step_slider, zone_chk, studio_state],
|
| 914 |
-
outputs=[slide_img, slide_guide, step_slider],
|
| 915 |
-
)
|
| 916 |
-
next_btn.click(
|
| 917 |
-
fn=next_slide,
|
| 918 |
-
inputs=[step_slider, zone_chk, studio_state],
|
| 919 |
-
outputs=[slide_img, slide_guide, step_slider],
|
| 920 |
-
)
|
| 921 |
-
color_dropdown.change(
|
| 922 |
-
fn=on_color_dropdown,
|
| 923 |
-
inputs=[color_dropdown, studio_state],
|
| 924 |
-
outputs=[color_loc_img, color_recipe_html],
|
| 925 |
-
)
|
| 926 |
-
clickable_img.select(
|
| 927 |
-
fn=on_canvas_click,
|
| 928 |
-
inputs=[studio_state],
|
| 929 |
-
outputs=[color_loc_img, color_recipe_html],
|
| 930 |
-
)
|
| 931 |
-
check_btn.click(
|
| 932 |
-
fn=evaluate_amateur_painting,
|
| 933 |
-
inputs=[in_img, user_canvas_in],
|
| 934 |
-
outputs=[feedback_img_out, feedback_md_out],
|
| 935 |
-
)
|
| 936 |
|
| 937 |
return demo
|
| 938 |
|
|
|
|
| 1 |
"""
|
| 2 |
+
hf_space/app.py — PaintPath Studio v2 (Flagship Edition) by Ali Jahani
|
| 3 |
100% Self-Contained Hugging Face Space & Local Runner.
|
| 4 |
|
| 5 |
+
Model : https://huggingface.co/tarfandoon/paintpath-net-v2 (60.6M, 512x512, 6 Native Stages + Aesthetic Score)
|
| 6 |
Author : Ali Jahani
|
| 7 |
Website : https://jahaniwww.com
|
| 8 |
Telegram: https://t.me/tarfandoonchannel
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
# ============================================================
|
| 43 |
+
# 1. PaintPathNetV2 Architecture (tarfandoon/paintpath-net-v2)
|
| 44 |
# ============================================================
|
| 45 |
class FiLMResBlock(nn.Module):
|
| 46 |
def __init__(self, in_ch: int, out_ch: int, cond_dim: int):
|
|
|
|
| 63 |
return F.gelu(h + self.skip(x))
|
| 64 |
|
| 65 |
|
| 66 |
+
class PaintPathNetV2(nn.Module, PyTorchModelHubMixin):
|
| 67 |
def __init__(
|
| 68 |
self,
|
| 69 |
backbone: str = "convnext_small.fb_in22k_ft_in1k",
|
| 70 |
pretrained: bool = False,
|
| 71 |
+
num_stages: int = 6,
|
| 72 |
cond_dim: int = 256,
|
| 73 |
):
|
| 74 |
super().__init__()
|
|
|
|
| 91 |
nn.Linear(cond_dim, cond_dim),
|
| 92 |
)
|
| 93 |
|
| 94 |
+
self.aesthetic_head = nn.Sequential(
|
| 95 |
+
nn.AdaptiveAvgPool2d(1),
|
| 96 |
+
nn.Flatten(),
|
| 97 |
+
nn.LayerNorm(chs[3]),
|
| 98 |
+
nn.Linear(chs[3], 128),
|
| 99 |
+
nn.GELU(),
|
| 100 |
+
nn.Dropout(0.15),
|
| 101 |
+
nn.Linear(128, 1),
|
| 102 |
+
nn.Sigmoid(),
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
self.bottleneck = FiLMResBlock(chs[3], 512, cond_dim)
|
| 106 |
self.dec3 = FiLMResBlock(512 + chs[2], 256, cond_dim)
|
| 107 |
self.dec2 = FiLMResBlock(256 + chs[1], 128, cond_dim)
|
|
|
|
| 120 |
self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
|
| 121 |
|
| 122 |
def extract_focal_map(self, img: torch.Tensor) -> torch.Tensor:
|
|
|
|
| 123 |
x_norm = (img - self.mean) / self.std
|
| 124 |
_, _, f3, f4 = self.encoder(x_norm)
|
| 125 |
m4 = torch.norm(f4, dim=1, keepdim=True)
|
|
|
|
| 132 |
m = (m - m.amin(dim=(-2, -1), keepdim=True)) / (m.amax(dim=(-2, -1), keepdim=True) - m.amin(dim=(-2, -1), keepdim=True) + 1e-6)
|
| 133 |
return m
|
| 134 |
|
| 135 |
+
def forward(self, img: torch.Tensor, stage_idx: torch.Tensor):
|
| 136 |
x_norm = (img - self.mean) / self.std
|
| 137 |
f1, f2, f3, f4 = self.encoder(x_norm)
|
| 138 |
cond = self.stage_emb(stage_idx)
|
| 139 |
+
aes_score = self.aesthetic_head(f4).squeeze(-1)
|
| 140 |
|
| 141 |
h = self.bottleneck(f4, cond)
|
| 142 |
h = F.interpolate(h, size=f3.shape[-2:], mode="bilinear", align_corners=False)
|
|
|
|
| 154 |
|
| 155 |
h = F.interpolate(h, size=(H, W), mode="bilinear", align_corners=False)
|
| 156 |
h = self.up_full(torch.cat([h, img], dim=1), cond)
|
| 157 |
+
return self.out_head(h), aes_score
|
| 158 |
|
| 159 |
|
| 160 |
# ============================================================
|
| 161 |
+
# 2. Physical Pigment Mixing, Centimeter Rulers & Animations
|
| 162 |
# ============================================================
|
| 163 |
ARTIST_TUBES: Dict[str, Tuple[int, int, int]] = {
|
| 164 |
"Titanium White": (245, 245, 242),
|
|
|
|
| 271 |
return img_rgb[top:bottom, left:right]
|
| 272 |
|
| 273 |
|
| 274 |
+
def polish_continuous_sketch(sketch_rgb: np.ndarray) -> np.ndarray:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
"""
|
| 276 |
+
Polishes PaintPathNetV2's continuous neural sketch so lines are crisp,
|
| 277 |
+
smooth, unbroken graphite strokes on warm art paper (ZERO dotted noise!).
|
|
|
|
| 278 |
"""
|
|
|
|
| 279 |
gray = cv2.cvtColor(sketch_rgb, cv2.COLOR_RGB2GRAY)
|
| 280 |
+
# Gentle morphological close on inverted lines reconnects any hairline gaps
|
| 281 |
+
inv = 255 - gray
|
| 282 |
+
inv = cv2.morphologyEx(inv, cv2.MORPH_CLOSE, np.ones((2, 2), np.uint8))
|
| 283 |
+
clean_g = 255 - inv
|
| 284 |
+
# Clean contrast stretch so paper is bright & lines are deep graphite
|
| 285 |
+
clean_g = np.clip((clean_g.astype(np.float32) - 25.0) * (255.0 / 215.0), 0, 255).astype(np.uint8)
|
| 286 |
+
# Subtle warm paper tint
|
| 287 |
+
out = np.stack([
|
| 288 |
+
clean_g,
|
| 289 |
+
np.clip(clean_g.astype(np.float32) * 0.99, 0, 255).astype(np.uint8),
|
| 290 |
+
np.clip(clean_g.astype(np.float32) * 0.96, 0, 255).astype(np.uint8),
|
| 291 |
+
], axis=-1)
|
| 292 |
+
return np.ascontiguousarray(out)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def draw_cm_ruler_grid(img_rgb: np.ndarray, width_cm: float, grid_n: int = 4) -> Tuple[np.ndarray, float, float, float]:
|
| 296 |
+
"""
|
| 297 |
+
Draws a clean real-world centimeter ruler border + 4x4 grid on the sketch
|
| 298 |
+
so the painter can measure exact proportions on their physical canvas with a ruler!
|
| 299 |
+
Returns: (annotated_img, height_cm, cell_w_cm, cell_h_cm)
|
| 300 |
+
"""
|
| 301 |
+
h, w = img_rgb.shape[:2]
|
| 302 |
+
height_cm = round(width_cm * (h / max(w, 1)), 1)
|
| 303 |
+
cell_w = round(width_cm / grid_n, 1)
|
| 304 |
+
cell_h = round(height_cm / grid_n, 1)
|
| 305 |
+
|
| 306 |
+
pad_top, pad_left = 30, 44
|
| 307 |
+
canvas = np.full((h + pad_top + 10, w + pad_left + 10, 3), 248, dtype=np.uint8)
|
| 308 |
+
canvas[pad_top : pad_top + h, pad_left : pad_left + w] = img_rgb
|
| 309 |
|
| 310 |
+
# Outer canvas border
|
| 311 |
+
cv2.rectangle(canvas, (pad_left, pad_top), (pad_left + w - 1, pad_top + h - 1), (55, 65, 81), 2)
|
|
|
|
| 312 |
|
| 313 |
+
# Crisp 4x4 proportion grid lines
|
| 314 |
+
for i in range(1, grid_n):
|
| 315 |
+
gx = pad_left + int(round(w * i / grid_n))
|
| 316 |
+
gy = pad_top + int(round(h * i / grid_n))
|
| 317 |
+
cv2.line(canvas, (gx, pad_top), (gx, pad_top + h - 1), (96, 150, 225), 1, cv2.LINE_AA)
|
| 318 |
+
cv2.line(canvas, (pad_left, gy), (pad_left + w - 1, gy), (96, 150, 225), 1, cv2.LINE_AA)
|
| 319 |
+
|
| 320 |
+
# Centimeter labels along top & left margins (ASCII-safe PIL bitmap font)
|
| 321 |
+
pil_im = Image.fromarray(canvas)
|
| 322 |
+
draw = ImageDraw.Draw(pil_im)
|
| 323 |
+
for i in range(grid_n + 1):
|
| 324 |
+
gx = pad_left + int(round(w * i / grid_n))
|
| 325 |
+
gy = pad_top + int(round(h * i / grid_n))
|
| 326 |
+
cm_x = round(width_cm * i / grid_n, 1)
|
| 327 |
+
cm_y = round(height_cm * i / grid_n, 1)
|
| 328 |
+
draw.text((max(2, gx - 14), 8), f"{cm_x:g}cm", fill=(30, 41, 59))
|
| 329 |
+
draw.text((4, max(pad_top - 4, gy - 6)), f"{cm_y:g}cm", fill=(30, 41, 59))
|
| 330 |
+
|
| 331 |
+
return np.ascontiguousarray(np.array(pil_im)), height_cm, cell_w, cell_h
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def make_smooth_sketch_animation(rough_rgb: np.ndarray, full_sketch_rgb: np.ndarray, width_cm: float) -> str:
|
| 335 |
+
"""
|
| 336 |
+
Smooth, accurate, non-dotted Pencil Sketching Animation GIF:
|
| 337 |
+
Phase A (0-45%): Draws the centimeter grid & progressively reveals Stage 0 main continuous lines
|
| 338 |
+
using a diagonal artist-hand sweep mask!
|
| 339 |
+
Phase B (45-100%): Smoothly layers in Stage 1 full continuous details!
|
| 340 |
+
"""
|
| 341 |
+
h, w = rough_rgb.shape[:2]
|
| 342 |
+
yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
|
| 343 |
+
# Natural top-left to bottom-right diagonal drawing sweep
|
| 344 |
+
sweep = (xx / max(w, 1)) * 0.55 + (yy / max(h, 1)) * 0.45
|
| 345 |
+
|
| 346 |
+
paper = np.full((h, w, 3), 250, dtype=np.uint8)
|
| 347 |
frames: List[Image.Image] = []
|
| 348 |
durations: List[int] = []
|
| 349 |
bar_h = 30
|
| 350 |
|
| 351 |
+
def _pack(arr: np.ndarray, title: str, pct: int) -> Image.Image:
|
| 352 |
+
grid_img, _, _, _ = draw_cm_ruler_grid(arr, width_cm, grid_n=4)
|
| 353 |
+
gh, gw = grid_img.shape[:2]
|
| 354 |
+
out = Image.new("RGB", (gw, gh + bar_h), (245, 240, 232))
|
| 355 |
+
out.paste(Image.fromarray(grid_img), (0, bar_h))
|
| 356 |
d = ImageDraw.Draw(out)
|
| 357 |
+
d.text((10, 7), f"{title} ({pct}%)", fill=(30, 35, 48))
|
| 358 |
+
prog = int((gw - 20) * pct / 100)
|
| 359 |
+
d.rectangle([10, bar_h - 5, gw - 10, bar_h - 2], fill=(220, 215, 205))
|
| 360 |
+
d.rectangle([10, bar_h - 5, 10 + prog, bar_h - 2], fill=(217, 119, 6))
|
|
|
|
| 361 |
return out
|
| 362 |
|
| 363 |
+
# Phase A: Continuous reveal of Stage 0 main structural outlines
|
| 364 |
+
for step in range(1, 9):
|
| 365 |
+
t = step / 8.0
|
| 366 |
+
alpha = np.clip((t * 1.15 - sweep) * 5.0, 0.0, 1.0)[..., None]
|
| 367 |
+
cur = np.clip(paper * (1.0 - alpha) + rough_rgb * alpha, 0, 255).astype(np.uint8)
|
| 368 |
+
frames.append(_pack(cur, "1. Main Proportions & Outlines", int(t * 48)))
|
|
|
|
|
|
|
|
|
|
| 369 |
durations.append(160)
|
| 370 |
|
| 371 |
+
# Phase B: Continuous reveal of Stage 1 full details on top of Stage 0
|
| 372 |
+
for step in range(1, 9):
|
| 373 |
+
t = step / 8.0
|
| 374 |
+
alpha = np.clip((t * 1.15 - sweep) * 5.0, 0.0, 1.0)[..., None]
|
| 375 |
+
cur = np.clip(rough_rgb * (1.0 - alpha) + full_sketch_rgb * alpha, 0, 255).astype(np.uint8)
|
| 376 |
+
frames.append(_pack(cur, "2. Refining Full Pencil Details", 48 + int(t * 52)))
|
| 377 |
+
durations.append(170)
|
| 378 |
+
|
| 379 |
+
# Hold final crisp sketch
|
| 380 |
+
frames.append(_pack(full_sketch_rgb, "Complete Sketch Ready for Paint", 100))
|
| 381 |
durations.append(2200)
|
| 382 |
|
| 383 |
tmp = tempfile.NamedTemporaryFile(suffix=".gif", delete=False)
|
|
|
|
| 387 |
|
| 388 |
|
| 389 |
def make_timelapse_gif(stages_7: List[np.ndarray]) -> str:
|
| 390 |
+
"""Smooth cinematic 7-stage painting timelapse GIF with progress bar."""
|
| 391 |
labels = [
|
| 392 |
+
"Step 1/7: Main Outlines & Grid",
|
| 393 |
+
"Step 2/7: Full Pencil Sketch",
|
| 394 |
+
"Step 3/7: Sepia Underpainting",
|
| 395 |
+
"Step 4/7: Broad Color Blocking",
|
| 396 |
+
"Step 5/7: Shadows & 3D Volume",
|
| 397 |
+
"Step 6/7: Mid-Details & Brushwork",
|
| 398 |
+
"Step 7/7: Final Highlights",
|
| 399 |
]
|
| 400 |
h, w = stages_7[0].shape[:2]
|
| 401 |
bar_h = 32
|
| 402 |
|
| 403 |
+
def _annotate(arr: np.ndarray, text: str, prog_frac: float) -> Image.Image:
|
| 404 |
+
canvas = Image.new("RGB", (w, h + bar_h), (245, 240, 232))
|
| 405 |
canvas.paste(Image.fromarray(arr), (0, bar_h))
|
| 406 |
+
d = ImageDraw.Draw(canvas)
|
| 407 |
+
d.text((10, 7), text, fill=(30, 35, 48))
|
| 408 |
+
prog = int((w - 20) * prog_frac)
|
| 409 |
+
d.rectangle([10, bar_h - 5, w - 10, bar_h - 2], fill=(220, 215, 205))
|
| 410 |
+
d.rectangle([10, bar_h - 5, 10 + prog, bar_h - 2], fill=(79, 70, 229))
|
| 411 |
return canvas
|
| 412 |
|
| 413 |
frames: List[Image.Image] = []
|
| 414 |
durations: List[int] = []
|
| 415 |
+
n = len(stages_7)
|
| 416 |
for i, img in enumerate(stages_7):
|
| 417 |
+
frames.append(_annotate(img, labels[i], (i + 1) / n))
|
| 418 |
+
durations.append(1100 if i < n - 1 else 2400)
|
| 419 |
+
if i < n - 1:
|
| 420 |
nxt = stages_7[i + 1]
|
| 421 |
+
for alpha in (0.25, 0.50, 0.75):
|
| 422 |
blend = cv2.addWeighted(img, 1.0 - alpha, nxt, alpha, 0)
|
| 423 |
+
frames.append(_annotate(blend, labels[i + 1], (i + 1 + alpha) / n))
|
| 424 |
+
durations.append(85)
|
| 425 |
|
| 426 |
tmp = tempfile.NamedTemporaryFile(suffix=".gif", delete=False)
|
| 427 |
tmp.close()
|
|
|
|
| 430 |
|
| 431 |
|
| 432 |
def make_clear_paint_zones(prev_img: np.ndarray, curr_img: np.ndarray) -> np.ndarray:
|
|
|
|
| 433 |
diff = np.mean(np.abs(curr_img.astype(np.float32) - prev_img.astype(np.float32)), axis=-1)
|
| 434 |
diff = cv2.GaussianBlur(diff, (7, 7), 0)
|
| 435 |
thr = max(9.0, float(np.percentile(diff, 68)))
|
|
|
|
| 437 |
bin_mask = cv2.morphologyEx(bin_mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
|
| 438 |
|
| 439 |
soft = cv2.GaussianBlur(bin_mask.astype(np.float32) / 255.0, (9, 9), 0)[..., None]
|
| 440 |
+
gray_bg = cv2.cvtColor(cv2.cvtColor(curr_img, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB).astype(np.float32) * 0.35 + 162.0
|
| 441 |
blended = np.ascontiguousarray(np.clip(gray_bg * (1.0 - soft) + curr_img.astype(np.float32) * soft, 0, 255).astype(np.uint8))
|
|
|
|
|
|
|
| 442 |
contours, _ = cv2.findContours(bin_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 443 |
cv2.drawContours(blended, contours, -1, (234, 88, 12), 2, cv2.LINE_AA)
|
| 444 |
return blended
|
|
|
|
| 462 |
return cv2.addWeighted(img_rgb, 0.50, heat_rgb, 0.50, 0)
|
| 463 |
|
| 464 |
|
| 465 |
+
def render_aesthetic_score_html(score_10: float, width_cm: float, height_cm: float, cell_w: float, cell_h: float) -> str:
|
| 466 |
+
pct = int(round(np.clip(score_10 * 10.0, 5, 100)))
|
| 467 |
+
if score_10 >= 8.0:
|
| 468 |
+
tier = "شاهکار و بسیار چشمگیر (جزو آثار برتر)"
|
| 469 |
+
bar_col = "#16a34a"
|
| 470 |
+
elif score_10 >= 6.5:
|
| 471 |
+
tier = "جذابیت بصری بالا و ترکیببندی قوی"
|
| 472 |
+
bar_col = "#d97706"
|
| 473 |
+
else:
|
| 474 |
+
tier = "متعادل و آرام (مناسب تمرین آماتور)"
|
| 475 |
+
bar_col = "#4f46e5"
|
| 476 |
+
|
| 477 |
+
return f"""
|
| 478 |
+
<div style="background:#fffdf9; border:2px solid #e7d5bc; border-radius:16px; padding:18px 22px; direction:rtl; color:#111827 !important;">
|
| 479 |
+
<div style="display:flex; flex-wrap:wrap; justify-content:space-between; align-items:center; gap:14px;">
|
| 480 |
+
<div>
|
| 481 |
+
<div style="font-size:13px; color:#6b7280 !important; font-weight:700;">امتیاز جذابیت و خیرگی بصری (آموزشدیده توسط PaintPathNet v2 روی ۵,۶۰۹ اثر)</div>
|
| 482 |
+
<div style="font-size:28px; font-weight:900; color:#111827 !important; margin-top:2px;">⭐ {score_10:.1f} <span style="font-size:15px; color:#6b7280 !important;">/ 10</span> — <span style="font-size:15px; color:{bar_col} !important;">{tier}</span></div>
|
| 483 |
+
</div>
|
| 484 |
+
<div style="background:#fef3c7; border:1px solid #f59e0b; border-radius:12px; padding:10px 16px; text-align:right;">
|
| 485 |
+
<div style="font-size:12px; color:#92400e !important; font-weight:700;">📐 ابعاد واقعی بوم و شبکه پیشنهادی</div>
|
| 486 |
+
<div style="font-size:15px; font-weight:800; color:#78350f !important;">بوم: {width_cm:g} × {height_cm:g} cm | هر خانه شبکه: {cell_w:g} × {cell_h:g} cm</div>
|
| 487 |
+
</div>
|
| 488 |
+
</div>
|
| 489 |
+
<div style="background:#e5e7eb; border-radius:999px; height:12px; overflow:hidden; margin-top:12px;">
|
| 490 |
+
<div style="width:{pct}%; height:100%; background:{bar_col}; border-radius:999px;"></div>
|
| 491 |
+
</div>
|
| 492 |
+
</div>
|
| 493 |
+
"""
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def highlight_target_rgb_on_canvas(img_rgb: np.ndarray, target_rgb: Tuple[int, int, int], tolerance: float = 25.0) -> Tuple[np.ndarray, str]:
|
| 497 |
img_lab = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2LAB).astype(np.float32)
|
| 498 |
t_lab = cv2.cvtColor(np.array([[target_rgb]], dtype=np.uint8), cv2.COLOR_RGB2LAB).astype(np.float32)[0, 0]
|
| 499 |
dist = np.linalg.norm(img_lab - t_lab[None, None, :], axis=-1)
|
|
|
|
| 502 |
mask_u8 = (mask > 0.45).astype(np.uint8) * 255
|
| 503 |
soft = cv2.GaussianBlur(mask.astype(np.float32), (7, 7), 0)[..., None]
|
| 504 |
|
| 505 |
+
bg = cv2.cvtColor(cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB).astype(np.float32) * 0.24 + 190.0
|
| 506 |
out = np.ascontiguousarray(np.clip(bg * (1.0 - soft) + img_rgb.astype(np.float32) * soft, 0, 255).astype(np.uint8))
|
| 507 |
contours, _ = cv2.findContours(mask_u8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 508 |
cv2.drawContours(out, contours, -1, (220, 38, 38), 1, cv2.LINE_AA)
|
|
|
|
| 517 |
fa_name = TUBE_PERSIAN.get(name, name)
|
| 518 |
bars_html += f"""
|
| 519 |
<div style="margin: 8px 0;">
|
| 520 |
+
<div style="display:flex; justify-content:space-between; font-size:13px; color:#1f2937 !important; font-weight:700;">
|
| 521 |
<span>🎨 {fa_name} ({name})</span>
|
| 522 |
<span>{pct}%</span>
|
| 523 |
</div>
|
| 524 |
<div style="background:#e5e7eb; border-radius:8px; height:12px; overflow:hidden; margin-top:3px;">
|
| 525 |
+
<div style="width:{pct}%; height:100%; background:rgb({tr},{tg},{tb}); border:1px solid rgba(0,0,0,0.18);"></div>
|
| 526 |
</div>
|
| 527 |
</div>
|
| 528 |
"""
|
|
|
|
| 533 |
<div style="width:56px; height:56px; border-radius:12px; background:{hex_code}; border:2px solid #374151; flex-shrink:0;"></div>
|
| 534 |
<div>
|
| 535 |
<div style="font-size:16px; font-weight:800; color:#111827 !important;">رنگ انتخابشده: <code>{hex_code}</code></div>
|
| 536 |
+
<div style="font-size:13px; color:#4b5563 !important;">RGB({r}, {g}, {b}) — کادرهای قرمز در تصویر دقیقاً تمام نقاطی هستند که باید این رنگ را بزنی!</div>
|
| 537 |
</div>
|
| 538 |
</div>
|
| 539 |
+
<div style="font-size:14px; font-weight:700; color:#111827 !important; margin-bottom:6px;">🧪 دستور ترکیب واقعی رنگهای تیوپی (Kubelka-Munk):</div>
|
| 540 |
{bars_html}
|
| 541 |
</div>
|
| 542 |
"""
|
|
|
|
| 581 |
struct_score = float(np.clip((corr + 0.2) * 85.0, 0, 100))
|
| 582 |
|
| 583 |
overall = 0.40 * color_score + 0.35 * value_score + 0.25 * struct_score
|
|
|
|
| 584 |
err_blur = cv2.GaussianBlur((np.clip(delta_e / 55.0, 0, 1) * 255).astype(np.uint8), (15, 15), 0)
|
| 585 |
heat = cv2.cvtColor(cv2.applyColorMap(err_blur, cv2.COLORMAP_JET), cv2.COLOR_BGR2RGB)
|
| 586 |
overlay = cv2.addWeighted(usr, 0.58, heat, 0.42, 0)
|
| 587 |
|
| 588 |
tips = []
|
| 589 |
if val_diff > 10:
|
| 590 |
+
tips.append("- **سایهها کمی روشناند:** روی نواحی قرمز، سایهها را با کمی قهوهای سوخته (Burnt Umber) عمیقتر کن.")
|
| 591 |
elif val_diff < -10:
|
| 592 |
tips.append("- **نقاشی کمی تیره شده:** در بخشهای روشن کمی سفید تیتانیوم اضافه کن.")
|
| 593 |
else:
|
| 594 |
tips.append("- **تعادل نور و سایه عالی است!**")
|
| 595 |
if color_score < 65:
|
| 596 |
+
tips.append("- **دقت رنگ:** در تب «قطرهچکان ساخت رنگ» روی بخشهای قرمز کلیک کن تا فرمول ترکیبش را ببینی.")
|
| 597 |
if struct_score < 55:
|
| 598 |
+
tips.append("- **تناسبات:** با خطکش سانتیمتری اسلاید ۱ جای اصلی اشیا را چک کن.")
|
| 599 |
|
| 600 |
report = (
|
| 601 |
+
f"### 🏆 امتیاز کلی کار دست تو: **{overall:.1f} / 100**\n"
|
| 602 |
f"- دقت رنگها: `{color_score:.1f}` | تعادل نور و سایه: `{value_score:.1f}` | تناسبات: `{struct_score:.1f}`\n\n"
|
| 603 |
f"#### 💡 توصیههای مربی (قرمز = نیاز به اصلاح، آبی = عالی):\n" + "\n".join(tips)
|
| 604 |
)
|
|
|
|
| 609 |
# 3. 7-Step Pedagogical Curriculum & Model Loading
|
| 610 |
# ============================================================
|
| 611 |
HERE = Path(__file__).resolve().parent
|
| 612 |
+
DEFAULT_HF_REPO = "tarfandoon/paintpath-net-v2"
|
| 613 |
ON_SPACES = bool(os.environ.get("SPACE_ID"))
|
| 614 |
MODEL = None
|
| 615 |
|
| 616 |
+
|
| 617 |
+
def build_step_guides(width_cm: float, height_cm: float, cell_w: float, cell_h: float) -> Dict[int, str]:
|
| 618 |
+
return {
|
| 619 |
+
1: (
|
| 620 |
+
f"### 📐 گام ۱ از ۷ — کادربندی به سانتیمتر و خطوط اصلی *(مداد HB، خیلی کمرنگ)*\n"
|
| 621 |
+
f"- **ابعاد بوم پیشنهادی:** `{width_cm:g} × {height_cm:g} cm` — روی بومت یک شبکه **4×4** با خانههای **`{cell_w:g} × {cell_h:g} cm`** بکش.\n"
|
| 622 |
+
f"- فقط خطوط پیوسته و اصلی تصویر را داخل هر خانه منتقل کن تا تناسبات ۱۰۰٪ دقیق شود."
|
| 623 |
+
),
|
| 624 |
+
2: (
|
| 625 |
+
f"### ✏️ گام ۲ از ۷ — اسکچ کامل مدادی *(مداد 2B)*\n"
|
| 626 |
+
f"- با کمک انیمیشن اسکچ سمت چپ، تمام جزئیات و فرمهای اصلی را روی طرح گام ۱ کامل کن.\n"
|
| 627 |
+
f"- خطوط اضافه شبکه را بعد از اطمینان از تناسبات با پاککن خمیری کمرنگ کن."
|
| 628 |
+
),
|
| 629 |
+
3: (
|
| 630 |
+
"### 🤎 گام ۳ از ۷ — زیررنگگذاری تکرنگ سپیا *(قلم تخت پهن #14 — حدود ۲.۵ سانتیمتر)*\n"
|
| 631 |
+
"- یک تکنیک اصیل استادان رنگروغن! فقط با **قهوهای سوخته (Burnt Umber) + کمی سفید**، سایهها و تیرگیهای اصلی را خیلی رقیق روی بوم بگذار تا حجم کار دربیاید."
|
| 632 |
+
),
|
| 633 |
+
4: (
|
| 634 |
+
"### 🖌️ گام ۴ از ۷ — رنگگذاری پایه و لکههای بزرگ *(قلم تخت #12 — حدود ۲ سانتیمتر)*\n"
|
| 635 |
+
"- از تب **قطرهچکان ساخت رنگ**، رنگ هر ناحیه بزرگ را بساز و کل بوم را با لکههای ساده و تخت پر کن (فعلاً سراغ جزئیات ریز نرو)."
|
| 636 |
+
),
|
| 637 |
+
5: (
|
| 638 |
+
"### 🌗 گام ۵ از ۷ — سایهها و حجم سهبعدی *(قلم متوسط #8 — حدود ۱ سانتیمتر)*\n"
|
| 639 |
+
"- تیک **«📍 نشان بده کجا را رنگ کنم»** را بزن! نواحی دارای کادر نارنجی دقیقاً جاهایی هستند که باید سایههای عمیقتر و حجم اضافه کنی."
|
| 640 |
+
),
|
| 641 |
+
6: (
|
| 642 |
+
"### ✨ گام ۶ از ۷ — جزئیات میانی و بافت قلممو *(قلم گرد #3 — حدود ۴ میلیمتر)*\n"
|
| 643 |
+
"- لبههای مهم را تمیز کن، بافت اشیا را بکش و انتقال بین رنگهای کنار هم را با قلم نرم محو کن."
|
| 644 |
+
),
|
| 645 |
+
7: (
|
| 646 |
+
"### 🌟 گام ۷ از ۷ — هایلایتها و ضربههای نهایی *(قلم ریز #0-#1 — ۱ تا ۲ میلیمتر)*\n"
|
| 647 |
+
"- با رنگ غلیظ و روشن، آخرین نقطههای نور و کنتراست تیز (نواحی کادر نارنجی) را بزن تا نقاشی زنده و تمام شود!"
|
| 648 |
+
),
|
| 649 |
+
}
|
| 650 |
|
| 651 |
|
| 652 |
def load_paintpath_model(model_dir: str = "", ckpt_path: str = "", hf_repo: str = ""):
|
|
|
|
| 655 |
init_dev = torch.device("cpu") if ON_SPACES else torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 656 |
|
| 657 |
if model_dir and Path(model_dir).exists() and (Path(model_dir) / "config.json").exists():
|
| 658 |
+
MODEL = PaintPathNetV2.from_pretrained(model_dir, pretrained=False).to(init_dev).eval()
|
| 659 |
return
|
| 660 |
|
| 661 |
repo = hf_repo or DEFAULT_HF_REPO
|
| 662 |
if repo:
|
| 663 |
+
MODEL = PaintPathNetV2.from_pretrained(repo, pretrained=False, token=token).to(init_dev).eval()
|
| 664 |
return
|
| 665 |
|
| 666 |
if ckpt_path and Path(ckpt_path).exists():
|
| 667 |
+
m = PaintPathNetV2(pretrained=False).to(init_dev)
|
| 668 |
ckpt = torch.load(ckpt_path, map_location=init_dev)
|
| 669 |
m.load_state_dict(ckpt["model"] if "model" in ckpt else ckpt)
|
| 670 |
MODEL = m.eval()
|
|
|
|
| 678 |
|
| 679 |
@_gpu_decorator
|
| 680 |
@torch.no_grad()
|
| 681 |
+
def run_paintpath_studio(input_img: np.ndarray, width_cm: float, num_colors: int):
|
| 682 |
if input_img is None or MODEL is None:
|
| 683 |
+
return None, "", None, None, None, "لطفاً ابتدا یک نقاشی آپلود کن.", 1, [], None, None, None, "", gr.update(), None, None
|
| 684 |
|
| 685 |
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 686 |
MODEL.to(dev)
|
| 687 |
|
| 688 |
clean = auto_crop_borders(input_img)
|
| 689 |
h, w = clean.shape[:2]
|
| 690 |
+
scale = 512.0 / max(h, w)
|
| 691 |
nw = max(64, (int(round(w * scale)) // 32) * 32)
|
| 692 |
nh = max(64, (int(round(h * scale)) // 32) * 32)
|
| 693 |
resized = cv2.resize(clean, (nw, nh), interpolation=cv2.INTER_AREA)
|
|
|
|
| 696 |
gpu_name = torch.cuda.get_device_name(0) if dev.type == "cuda" else ""
|
| 697 |
use_amp = (dev.type == "cuda") and ("1650" not in gpu_name and "1660" not in gpu_name)
|
| 698 |
|
| 699 |
+
# Run all 6 native PaintPathNetV2 stages + Real Aesthetic Score + Deep Focal Map!
|
| 700 |
+
stages_v2 = []
|
| 701 |
+
aes_val = 7.5
|
| 702 |
with torch.amp.autocast("cuda", enabled=use_amp, dtype=torch.float16):
|
| 703 |
focal_t = MODEL.extract_focal_map(inp)
|
| 704 |
+
for s_idx in range(6):
|
| 705 |
st = torch.tensor([s_idx], dtype=torch.long, device=dev)
|
| 706 |
+
pred, aes = MODEL(inp, st)
|
| 707 |
+
if s_idx == 0:
|
| 708 |
+
aes_val = float(aes[0].float().clamp(0, 1).item()) * 10.0
|
| 709 |
arr = np.ascontiguousarray((pred[0].float().clamp(0, 1).permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8))
|
| 710 |
+
stages_v2.append(arr)
|
| 711 |
|
| 712 |
focal_01 = focal_t[0, 0].float().cpu().numpy()
|
| 713 |
+
m_rough = polish_continuous_sketch(stages_v2[0])
|
| 714 |
+
m_sketch = polish_continuous_sketch(stages_v2[1])
|
| 715 |
+
m_sepia = stages_v2[2]
|
| 716 |
+
m_block = stages_v2[3]
|
| 717 |
+
m_shadow = stages_v2[4]
|
| 718 |
+
m_detail = stages_v2[5]
|
| 719 |
+
|
| 720 |
+
# Add real-world centimeter ruler & 4x4 grid to Stage 1 & Stage 2!
|
| 721 |
+
st1_cm, height_cm, cell_w, cell_h = draw_cm_ruler_grid(m_rough, float(width_cm), grid_n=4)
|
| 722 |
+
st2_cm, _, _, _ = draw_cm_ruler_grid(m_sketch, float(width_cm), grid_n=4)
|
| 723 |
+
|
| 724 |
+
guides = build_step_guides(float(width_cm), height_cm, cell_w, cell_h)
|
| 725 |
+
score_html = render_aesthetic_score_html(aes_val, float(width_cm), height_cm, cell_w, cell_h)
|
| 726 |
+
|
| 727 |
+
# Smooth animations (both continuous pencil reveal & 7-stage timelapse)
|
| 728 |
+
sketch_gif = make_smooth_sketch_animation(m_rough, m_sketch, float(width_cm))
|
| 729 |
+
timelapse_gif = make_timelapse_gif([m_rough, m_sketch, m_sepia, m_block, m_shadow, m_detail, resized])
|
| 730 |
+
|
| 731 |
+
step_imgs = {1: st1_cm, 2: st2_cm, 3: m_sepia, 4: m_block, 5: m_shadow, 6: m_detail, 7: resized}
|
| 732 |
blank = np.full_like(resized, 248)
|
| 733 |
paint_zones = {
|
| 734 |
+
1: st1_cm,
|
| 735 |
+
2: st2_cm,
|
| 736 |
+
3: make_clear_paint_zones(blank, m_sepia),
|
| 737 |
+
4: make_clear_paint_zones(m_sepia, m_block),
|
| 738 |
+
5: make_clear_paint_zones(m_block, m_shadow),
|
| 739 |
+
6: make_clear_paint_zones(m_shadow, m_detail),
|
| 740 |
+
7: make_clear_paint_zones(m_detail, resized),
|
| 741 |
}
|
| 742 |
|
| 743 |
+
gallery_items = [
|
| 744 |
+
(st1_cm, "۱. کادر و خطوط اصلی (cm)"),
|
| 745 |
+
(st2_cm, "۲. اسکچ کامل مدادی"),
|
| 746 |
+
(m_sepia, "۳. زیررنگ سپیا"),
|
| 747 |
+
(m_block, "۴. رنگگذاری پایه"),
|
| 748 |
+
(m_shadow, "۵. سایهها و حجم"),
|
| 749 |
+
(m_detail, "۶. جزئیات میانی"),
|
| 750 |
+
(resized, "۷. نقاشی نهایی"),
|
| 751 |
+
]
|
| 752 |
+
|
| 753 |
palette = extract_physical_palette(resized, k=int(num_colors))
|
| 754 |
pal_card = render_palette_card(palette)
|
| 755 |
loc_img, loc_html = highlight_target_rgb_on_canvas(resized, palette[0].rgb)
|
|
|
|
| 762 |
"resized": resized,
|
| 763 |
"step_imgs": step_imgs,
|
| 764 |
"paint_zones": paint_zones,
|
| 765 |
+
"guides": guides,
|
| 766 |
"palette": palette,
|
| 767 |
}
|
| 768 |
|
| 769 |
return (
|
| 770 |
state,
|
| 771 |
+
score_html,
|
| 772 |
sketch_gif,
|
| 773 |
timelapse_gif,
|
| 774 |
step_imgs[1],
|
| 775 |
+
guides[1],
|
| 776 |
1,
|
| 777 |
+
gallery_items,
|
| 778 |
resized,
|
| 779 |
pal_card,
|
| 780 |
loc_img,
|
|
|
|
| 790 |
return None, "ابتدا یک نقاشی آپلود کن.", 1
|
| 791 |
s = max(1, min(7, int(step_num)))
|
| 792 |
img = state["paint_zones"][s] if show_zones else state["step_imgs"][s]
|
| 793 |
+
return img, state["guides"][s], s
|
| 794 |
|
| 795 |
|
| 796 |
def prev_slide(step_num: int, show_zones: bool, state: Optional[dict]):
|
|
|
|
| 813 |
|
| 814 |
|
| 815 |
def on_canvas_click(state: Optional[dict], evt: gr.SelectData):
|
|
|
|
| 816 |
if not state:
|
| 817 |
return None, "<p>ابتدا نقاشی را تحلیل کن.</p>"
|
| 818 |
img = state["resized"]
|
| 819 |
x, y = int(evt.index[0]), int(evt.index[1])
|
| 820 |
h, w = img.shape[:2]
|
| 821 |
+
x, y = max(0, min(x, w - 1)), max(0, min(y, h - 1))
|
|
|
|
|
|
|
| 822 |
patch = img[max(0, y - 2) : min(h, y + 3), max(0, x - 2) : min(w, x + 3)]
|
| 823 |
mean_rgb = tuple(int(round(v)) for v in patch.reshape(-1, 3).mean(axis=0))
|
| 824 |
return highlight_target_rgb_on_canvas(img, mean_rgb, tolerance=24.0)
|
| 825 |
|
| 826 |
|
| 827 |
# ============================================================
|
| 828 |
+
# 4. Crisp, High-Contrast Flagship UI (Light & Dark Mode Safe)
|
| 829 |
# ============================================================
|
| 830 |
CUSTOM_CSS = """
|
| 831 |
.studio-hero {
|
| 832 |
+
background: linear-gradient(135deg, #fff9ef 0%, #fef2dc 50%, #eef2ff 100%) !important;
|
| 833 |
+
border: 2px solid #e5d1b3 !important;
|
| 834 |
+
border-radius: 22px !important;
|
| 835 |
+
padding: 26px 30px !important;
|
| 836 |
margin-bottom: 18px !important;
|
| 837 |
text-align: center !important;
|
| 838 |
+
box-shadow: 0 10px 28px rgba(15, 23, 42, 0.06) !important;
|
| 839 |
}
|
| 840 |
.studio-hero h1 {
|
| 841 |
margin: 0 0 8px 0 !important;
|
| 842 |
+
font-size: 2.1rem !important;
|
| 843 |
font-weight: 900 !important;
|
| 844 |
color: #111827 !important;
|
| 845 |
}
|
| 846 |
.studio-hero p {
|
| 847 |
margin: 0 auto 16px auto !important;
|
| 848 |
+
max-width: 780px !important;
|
| 849 |
font-size: 1.04rem !important;
|
| 850 |
font-weight: 500 !important;
|
| 851 |
color: #374151 !important;
|
|
|
|
| 860 |
display: inline-flex !important;
|
| 861 |
align-items: center !important;
|
| 862 |
gap: 6px !important;
|
| 863 |
+
padding: 8px 16px !important;
|
| 864 |
border-radius: 999px !important;
|
| 865 |
background: #1f2937 !important;
|
| 866 |
color: #ffffff !important;
|
| 867 |
text-decoration: none !important;
|
| 868 |
font-size: 0.88rem !important;
|
| 869 |
font-weight: 700 !important;
|
|
|
|
| 870 |
}
|
| 871 |
.brand-links a:hover {
|
| 872 |
background: #d97706 !important;
|
|
|
|
| 874 |
}
|
| 875 |
.studio-footer {
|
| 876 |
text-align: center !important;
|
| 877 |
+
margin-top: 26px !important;
|
| 878 |
padding: 16px !important;
|
| 879 |
+
background: #fff9ef !important;
|
| 880 |
+
border: 1px solid #e5d1b3 !important;
|
| 881 |
border-radius: 14px !important;
|
| 882 |
color: #1f2937 !important;
|
| 883 |
+
font-size: 0.94rem !important;
|
| 884 |
font-weight: 600 !important;
|
| 885 |
}
|
| 886 |
.studio-footer a {
|
| 887 |
color: #b45309 !important;
|
| 888 |
text-decoration: none !important;
|
| 889 |
+
font-weight: 800 !important;
|
| 890 |
}
|
| 891 |
"""
|
| 892 |
|
| 893 |
|
| 894 |
def build_ui():
|
| 895 |
+
with gr.Blocks(title="PaintPath Studio v2 — Ali Jahani") as demo:
|
| 896 |
studio_state = gr.State(value=None)
|
| 897 |
|
| 898 |
gr.HTML(
|
| 899 |
"""
|
| 900 |
<div class="studio-hero">
|
| 901 |
+
<h1>🎨 PaintPath Studio v2 — هوش مصنوعی مربی نقاشی تو</h1>
|
| 902 |
+
<p>همیشه انسان کار را برای هوش مصنوعی ساده میکند؛ این بار هوش مصنوعی نقاشی را با <b>خطکش واقعی به سانتیمتر، انیمیشن اسکچ، ۷ مرحله آموزشی و فرمول ساخت رنگ</b> ساده میکند تا تو نقاش بشوی!</p>
|
| 903 |
<div class="brand-links">
|
| 904 |
<a href="https://jahaniwww.com" target="_blank">👤 Ali Jahani — jahaniwww.com</a>
|
| 905 |
<a href="https://t.me/tarfandoonchannel" target="_blank">✈️ Telegram: @tarfandoonchannel</a>
|
| 906 |
+
<a href="https://huggingface.co/tarfandoon/paintpath-net-v2" target="_blank">🤗 Model: PaintPathNet v2 (512px)</a>
|
| 907 |
</div>
|
| 908 |
</div>
|
| 909 |
"""
|
| 910 |
)
|
| 911 |
|
| 912 |
+
# Clean Upload + Canvas Size Bar
|
| 913 |
with gr.Row(equal_height=True):
|
| 914 |
with gr.Column(scale=2):
|
| 915 |
in_img = gr.Image(type="numpy", label="۱. نقاشی مورد نظرت را اینجا آپلود کن", height=270)
|
| 916 |
with gr.Column(scale=1):
|
| 917 |
+
gr.Markdown("### 📐 تنظیم بوم واقعی و شروع")
|
| 918 |
+
width_cm = gr.Slider(15, 100, value=40, step=5, label="عرض بوم واقعی تو (سانتیمتر)")
|
| 919 |
+
num_colors = gr.Slider(6, 12, value=8, step=1, label="تعداد رنگهای پالت اصلی")
|
| 920 |
+
run_btn = gr.Button("✨ ساخت نقشه ۷ مرحلهای + تحلیل کامل", variant="primary", size="lg")
|
| 921 |
+
|
| 922 |
+
score_banner = gr.HTML("")
|
| 923 |
|
| 924 |
with gr.Tabs():
|
| 925 |
+
# TAB 1: Interactive 7-Stage Slides + Smooth Animations
|
| 926 |
+
with gr.Tab("🎬 ۱. آموزش ۷ مرحلهای + انیمیشن اسکچ و فیلم"):
|
| 927 |
with gr.Row():
|
| 928 |
with gr.Column(scale=1):
|
| 929 |
+
gr.Markdown("### 🖼️ اسلاید تعاملی ۷ مرحلهای (با ابعاد سانتیمتر)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 930 |
slide_img = gr.Image(label="بوم هدف در مرحله فعلی", interactive=False)
|
| 931 |
with gr.Row():
|
| 932 |
prev_btn = gr.Button("⬅️ مرحله قبل")
|
| 933 |
next_btn = gr.Button("مرحله بعد ➡️", variant="primary")
|
| 934 |
with gr.Row():
|
| 935 |
+
step_slider = gr.Slider(1, 7, value=1, step=1, label="شماره مرحله (۱ تا ۷)")
|
| 936 |
+
zone_chk = gr.Checkbox(value=False, label="📍 نشان بده در این مرحله کجا را رنگ کنم!")
|
| 937 |
+
slide_guide = gr.Markdown("پس از آپلود نقاشی، اینجا راهنمای دقیق هر مرحله (با سایز قلممو و ابعاد بوم به سانتیمتر) نمایش داده میشود.")
|
| 938 |
+
|
| 939 |
+
with gr.Column(scale=1):
|
| 940 |
+
gr.Markdown("### ✏️ انیمیشن روان اسکچ کشیدن (خطوط پیوسته)")
|
| 941 |
+
sketch_gif_out = gr.Image(label="ترسیم مرحلهبهمرحله خطوط اصلی و جزئیات", interactive=False)
|
| 942 |
+
gr.Markdown("### 🎥 فیلم تایملپس کامل ۷ مرحلهای")
|
| 943 |
+
timelapse_out = gr.Image(label="سفر کامل از خطوط اولیه تا نقاشی نهایی", interactive=False)
|
| 944 |
+
|
| 945 |
+
gr.Markdown("#### 🗺️ نمای یکپارچه هر ۷ مرحله کنار هم:")
|
| 946 |
+
gallery_out = gr.Gallery(columns=7, height=190, label="مسیر کامل نقاشی")
|
| 947 |
|
| 948 |
# TAB 2: Interactive Click-to-Extract Color Mixer & Canvas Locator
|
| 949 |
+
with gr.Tab("🎨 ۲. قطرهچکان ساخت رنگ تعاملی (کلیک روی نقاشی!)"):
|
| 950 |
+
gr.Markdown("### 💧 روی هر نقطهای از نقاشی سمت چپ کلیک کن تا **فرمول دقیق ترکیب رنگ تیوپیاش** و **تمام جاهایی که آن رنگ روی بوم هست** را ببینی!")
|
| 951 |
with gr.Row():
|
| 952 |
+
clickable_img = gr.Image(label="👆 روی هر نقطه نقاشی کلیک کن", interactive=False)
|
| 953 |
color_loc_img = gr.Image(label="📍 تمام نقاطی که باید این رنگ را بزنی (کادر قرمز)", interactive=False)
|
| 954 |
with gr.Row():
|
| 955 |
with gr.Column(scale=1):
|
| 956 |
+
color_dropdown = gr.Dropdown(choices=[], label="یا از رنگهای اصلی پالت انتخاب کن:", interactive=True)
|
| 957 |
+
color_recipe_html = gr.HTML("<div style='padding:12px; color:#4b5563;'>روی هر نقطهای از نقاشی کلیک کن تا دستور ساخت رنگش را ببینی.</div>")
|
| 958 |
with gr.Column(scale=1):
|
| 959 |
pal_out = gr.Image(label="کارت کامل پالت رنگ فیزیکی")
|
| 960 |
|
| 961 |
+
# TAB 3: Dedicated Eye Attention, Aesthetic Score & Value Study
|
| 962 |
with gr.Tab("👁️ ۳. کانون توجه چ��م و نورپردازی"):
|
| 963 |
gr.Markdown(
|
| 964 |
+
"### 🔥 نگاهِ مغز هوش مصنوعی به نقاشی\n"
|
| 965 |
+
"مدل **`PaintPathNet v2`** نشان میدهد **چشم مخاطب اول به کجا خیره میشود** (نواحی زرد و قرمز) و در کنارش **مطالعه ۳ سطحی نور و سایه** را میدهد."
|
| 966 |
)
|
| 967 |
with gr.Row():
|
| 968 |
+
attn_out = gr.Image(label="🔥 نقشه کانون توجه چشم (ConvNeXt Deep Focal Map)")
|
| 969 |
val_out = gr.Image(label="🌗 مطالعه ارزش نوری ۳ سطحی (تیره / میانی / روشن)")
|
| 970 |
|
| 971 |
# TAB 4: Check My Hand-Painted Canvas
|
| 972 |
with gr.Tab("🏆 ۴. ارزیابی نقاشیِ دستِ تو"):
|
| 973 |
+
gr.Markdown("از نقاشیای که خودت با دست روی بوم یا کاغذ کشیدی عکس بگیر و اینجا آپلود کن تا **امتیاز ۰ تا ۱۰۰ و نقشه اصلاح** بگیری!")
|
| 974 |
with gr.Row():
|
| 975 |
user_canvas_in = gr.Image(type="numpy", label="📸 عکس نقاشیِ دستِ خودت")
|
| 976 |
feedback_img_out = gr.Image(label="🔍 نقشه اصلاح (قرمز = نیاز به اصلاح، آبی = عالی)")
|
|
|
|
| 990 |
# Events
|
| 991 |
run_btn.click(
|
| 992 |
fn=run_paintpath_studio,
|
| 993 |
+
inputs=[in_img, width_cm, num_colors],
|
| 994 |
outputs=[
|
| 995 |
studio_state,
|
| 996 |
+
score_banner,
|
| 997 |
sketch_gif_out,
|
| 998 |
timelapse_out,
|
| 999 |
slide_img,
|
| 1000 |
slide_guide,
|
| 1001 |
step_slider,
|
| 1002 |
+
gallery_out,
|
| 1003 |
clickable_img,
|
| 1004 |
pal_out,
|
| 1005 |
color_loc_img,
|
|
|
|
| 1010 |
],
|
| 1011 |
)
|
| 1012 |
|
| 1013 |
+
step_slider.change(render_slide, [step_slider, zone_chk, studio_state], [slide_img, slide_guide, step_slider])
|
| 1014 |
+
zone_chk.change(render_slide, [step_slider, zone_chk, studio_state], [slide_img, slide_guide, step_slider])
|
| 1015 |
+
prev_btn.click(prev_slide, [step_slider, zone_chk, studio_state], [slide_img, slide_guide, step_slider])
|
| 1016 |
+
next_btn.click(next_slide, [step_slider, zone_chk, studio_state], [slide_img, slide_guide, step_slider])
|
| 1017 |
+
color_dropdown.change(on_color_dropdown, [color_dropdown, studio_state], [color_loc_img, color_recipe_html])
|
| 1018 |
+
clickable_img.select(on_canvas_click, [studio_state], [color_loc_img, color_recipe_html])
|
| 1019 |
+
check_btn.click(evaluate_amateur_painting, [in_img, user_canvas_in], [feedback_img_out, feedback_md_out])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1020 |
|
| 1021 |
return demo
|
| 1022 |
|