""" hf_space/app.py — PaintPath Studio v2 (Flagship Edition) by Ali Jahani 100% Self-Contained Hugging Face Space & Local Runner. Model : https://huggingface.co/tarfandoon/paintpath-net-v2 (60.6M, 512x512, 6 Native Stages + Aesthetic Score) Author : Ali Jahani Website : https://jahaniwww.com Telegram: https://t.me/tarfandoonchannel """ import argparse import base64 import html as html_lib import io import os import tempfile from dataclasses import dataclass from pathlib import Path from typing import Dict, List, Optional, Tuple # On Hugging Face ZeroGPU Spaces, `spaces` MUST be imported before `torch`! try: import spaces except ImportError: spaces = None import cv2 import gradio as gr import numpy as np import timm import torch import torch.nn as nn import torch.nn.functional as F from PIL import Image, ImageDraw from scipy.optimize import minimize from sklearn.cluster import KMeans try: from huggingface_hub import PyTorchModelHubMixin except ImportError: class PyTorchModelHubMixin: pass # ============================================================ # 1. PaintPathNetV2 Architecture (tarfandoon/paintpath-net-v2) # ============================================================ class FiLMResBlock(nn.Module): def __init__(self, in_ch: int, out_ch: int, cond_dim: int): super().__init__() num_groups = next(g for g in (32, 16, 8, 4, 2, 1) if out_ch % g == 0) self.conv1 = nn.Conv2d(in_ch, out_ch, kernel_size=3, padding=1, bias=False) self.norm1 = nn.GroupNorm(num_groups, out_ch) self.conv2 = nn.Conv2d(out_ch, out_ch, kernel_size=3, padding=1, bias=False) self.norm2 = nn.GroupNorm(num_groups, out_ch) self.film = nn.Linear(cond_dim, out_ch * 2) nn.init.zeros_(self.film.weight) nn.init.zeros_(self.film.bias) self.skip = nn.Conv2d(in_ch, out_ch, kernel_size=1) if in_ch != out_ch else nn.Identity() def forward(self, x: torch.Tensor, cond: torch.Tensor) -> torch.Tensor: h = F.gelu(self.norm1(self.conv1(x))) gamma, beta = self.film(cond).chunk(2, dim=-1) h = self.norm2(self.conv2(h)) h = h * (1.0 + gamma[:, :, None, None]) + beta[:, :, None, None] return F.gelu(h + self.skip(x)) class PaintPathNetV2(nn.Module, PyTorchModelHubMixin): def __init__( self, backbone: str = "convnext_small.fb_in22k_ft_in1k", pretrained: bool = False, num_stages: int = 6, cond_dim: int = 256, ): super().__init__() self.backbone = backbone self.num_stages = num_stages self.cond_dim = cond_dim self.encoder = timm.create_model( backbone, pretrained=pretrained, features_only=True, out_indices=(0, 1, 2, 3), ) chs = self.encoder.feature_info.channels() self.stage_emb = nn.Sequential( nn.Embedding(num_stages, cond_dim), nn.Linear(cond_dim, cond_dim), nn.GELU(), nn.Linear(cond_dim, cond_dim), ) self.aesthetic_head = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.LayerNorm(chs[3]), nn.Linear(chs[3], 128), nn.GELU(), nn.Dropout(0.15), nn.Linear(128, 1), nn.Sigmoid(), ) self.bottleneck = FiLMResBlock(chs[3], 512, cond_dim) self.dec3 = FiLMResBlock(512 + chs[2], 256, cond_dim) self.dec2 = FiLMResBlock(256 + chs[1], 128, cond_dim) self.dec1 = FiLMResBlock(128 + chs[0], 96, cond_dim) self.up_half = FiLMResBlock(96, 64, cond_dim) self.up_full = FiLMResBlock(64 + 3, 48, cond_dim) self.out_head = nn.Sequential( nn.Conv2d(48, 32, kernel_size=3, padding=1), nn.GELU(), nn.Conv2d(32, 3, kernel_size=1), nn.Sigmoid(), ) self.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)) self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)) def extract_focal_map(self, img: torch.Tensor) -> torch.Tensor: x_norm = (img - self.mean) / self.std _, _, f3, f4 = self.encoder(x_norm) m4 = torch.norm(f4, dim=1, keepdim=True) m3 = torch.norm(f3, dim=1, keepdim=True) H, W = img.shape[-2], img.shape[-1] m4 = F.interpolate(m4, size=(H, W), mode="bilinear", align_corners=False) m3 = F.interpolate(m3, size=(H, W), mode="bilinear", align_corners=False) m = 0.65 * (m4 / (m4.amax(dim=(-2, -1), keepdim=True) + 1e-6)) + \ 0.35 * (m3 / (m3.amax(dim=(-2, -1), keepdim=True) + 1e-6)) 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) return m def forward(self, img: torch.Tensor, stage_idx: torch.Tensor): x_norm = (img - self.mean) / self.std f1, f2, f3, f4 = self.encoder(x_norm) cond = self.stage_emb(stage_idx) aes_score = self.aesthetic_head(f4).squeeze(-1) h = self.bottleneck(f4, cond) h = F.interpolate(h, size=f3.shape[-2:], mode="bilinear", align_corners=False) h = self.dec3(torch.cat([h, f3], dim=1), cond) h = F.interpolate(h, size=f2.shape[-2:], mode="bilinear", align_corners=False) h = self.dec2(torch.cat([h, f2], dim=1), cond) h = F.interpolate(h, size=f1.shape[-2:], mode="bilinear", align_corners=False) h = self.dec1(torch.cat([h, f1], dim=1), cond) H, W = img.shape[-2], img.shape[-1] h = F.interpolate(h, size=(H // 2, W // 2), mode="bilinear", align_corners=False) h = self.up_half(h, cond) h = F.interpolate(h, size=(H, W), mode="bilinear", align_corners=False) h = self.up_full(torch.cat([h, img], dim=1), cond) return self.out_head(h), aes_score # ============================================================ # 2. Physical Pigment Mixing, Centimeter Rulers & Animations # ============================================================ ARTIST_TUBES: Dict[str, Tuple[int, int, int]] = { "Titanium White": (245, 245, 242), "Ivory Black": (28, 28, 30), "Ultramarine Blue": (25, 45, 145), "Cadmium Red": (208, 38, 32), "Cadmium Yellow": (242, 200, 28), "Yellow Ochre": (198, 146, 58), "Burnt Umber": (84, 52, 34), "Viridian Green": (34, 118, 88), } TUBE_PERSIAN = { "Titanium White": "سفید تیتانیوم", "Ivory Black": "مشکی عاجی", "Ultramarine Blue": "آبی اولترامارین", "Cadmium Red": "قرمز کادمیوم", "Cadmium Yellow": "زرد کادمیوم", "Yellow Ochre": "زرد اخرایی", "Burnt Umber": "قهوه‌ای سوخته (آمبر)", "Viridian Green": "سبز ویریدین", } def _srgb_to_linear(rgb01: np.ndarray) -> np.ndarray: return np.where(rgb01 <= 0.04045, rgb01 / 12.92, ((rgb01 + 0.055) / 1.055) ** 2.4) def _linear_to_ks(r: np.ndarray) -> np.ndarray: r = np.clip(r, 1e-3, 0.999) return ((1.0 - r) ** 2) / (2.0 * r) def solve_tube_recipe(target_rgb: Tuple[int, int, int], max_tubes: int = 3) -> List[Tuple[str, int]]: names = list(ARTIST_TUBES.keys()) tube_lin = _srgb_to_linear(np.array([ARTIST_TUBES[n] for n in names], dtype=np.float64) / 255.0) tube_ks = _linear_to_ks(tube_lin) tgt_lin = _srgb_to_linear(np.array(target_rgb, dtype=np.float64) / 255.0) def _fit(sub_ks: np.ndarray) -> np.ndarray: m = len(sub_ks) def loss_fn(w): ks = np.maximum(w @ sub_ks, 1e-4) pred_r = 1.0 + ks - np.sqrt(ks * ks + 2.0 * ks) return float(np.sum((pred_r - tgt_lin) ** 2)) res = minimize( loss_fn, x0=np.ones(m, dtype=np.float64) / m, bounds=[(0.0, 1.0)] * m, constraints={"type": "eq", "fun": lambda w: np.sum(w) - 1.0}, method="SLSQP", options={"ftol": 1e-9, "maxiter": 150}, ) w = np.maximum(res.x, 0.0) return w / (w.sum() + 1e-12) w = _fit(tube_ks) top_idx = np.argsort(w)[::-1][:max_tubes] sw = _fit(tube_ks[top_idx]) recipe = [(names[idx], int(round(weight * 100))) for idx, weight in zip(top_idx, sw) if int(round(weight * 100)) >= 5] if recipe: total = sum(p for _, p in recipe) if total != 100: recipe[0] = (recipe[0][0], recipe[0][1] + (100 - total)) return recipe @dataclass class PaletteColor: index: int rgb: Tuple[int, int, int] hex: str proportion: float mixing_recipe: List[Tuple[str, int]] def extract_physical_palette(image_rgb: np.ndarray, k: int = 8, seed: int = 42) -> List[PaletteColor]: small = cv2.resize(image_rgb, (128, 128), interpolation=cv2.INTER_AREA) lab = cv2.cvtColor(small, cv2.COLOR_RGB2LAB).reshape(-1, 3).astype(np.float32) km = KMeans(n_clusters=k, n_init=5, random_state=seed) labels = km.fit_predict(lab) centers_rgb = cv2.cvtColor(np.clip(km.cluster_centers_, 0, 255).astype(np.uint8).reshape(1, k, 3), cv2.COLOR_LAB2RGB).reshape(k, 3) props = np.bincount(labels, minlength=k).astype(np.float64) props /= props.sum() palette: List[PaletteColor] = [] for new_i, idx in enumerate(np.argsort(-props)): r, g, b = int(centers_rgb[idx, 0]), int(centers_rgb[idx, 1]), int(centers_rgb[idx, 2]) 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)))) return palette def auto_crop_borders(img_rgb: np.ndarray, tol: int = 18, max_crop_ratio: float = 0.15) -> np.ndarray: h, w = img_rgb.shape[:2] gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY) is_br = (gray.std(axis=1) < 8.0) & ((gray.mean(axis=1) > 255 - tol) | (gray.mean(axis=1) < tol)) is_bc = (gray.std(axis=0) < 8.0) & ((gray.mean(axis=0) > 255 - tol) | (gray.mean(axis=0) < tol)) top, bottom, left, right = 0, h, 0, w while top < int(h * max_crop_ratio) and is_br[top]: top += 1 while bottom > h - int(h * max_crop_ratio) and is_br[bottom - 1]: bottom -= 1 while left < int(w * max_crop_ratio) and is_bc[left]: left += 1 while right > w - int(w * max_crop_ratio) and is_bc[right - 1]: right -= 1 if bottom - top < h * 0.6 or right - left < w * 0.6: return img_rgb return img_rgb[top:bottom, left:right] def polish_continuous_sketch(sketch_rgb: np.ndarray) -> np.ndarray: """ Polishes PaintPathNetV2's continuous neural sketch so lines are crisp, smooth, unbroken graphite strokes on warm art paper (ZERO dotted noise!). """ gray = cv2.cvtColor(sketch_rgb, cv2.COLOR_RGB2GRAY) # Gentle morphological close on inverted lines reconnects any hairline gaps inv = 255 - gray inv = cv2.morphologyEx(inv, cv2.MORPH_CLOSE, np.ones((2, 2), np.uint8)) clean_g = 255 - inv # Clean contrast stretch so paper is bright & lines are deep graphite clean_g = np.clip((clean_g.astype(np.float32) - 25.0) * (255.0 / 215.0), 0, 255).astype(np.uint8) # Subtle warm paper tint out = np.stack([ clean_g, np.clip(clean_g.astype(np.float32) * 0.99, 0, 255).astype(np.uint8), np.clip(clean_g.astype(np.float32) * 0.96, 0, 255).astype(np.uint8), ], axis=-1) return np.ascontiguousarray(out) def upscale_hi_res(img_rgb: np.ndarray, target_max: int = 1024, sharpen: bool = True) -> np.ndarray: """Crisp Lanczos upscale to ~1024px so Maximize/Fullscreen & Zoom show rich detail.""" h, w = img_rgb.shape[:2] if max(h, w) >= target_max: return np.ascontiguousarray(img_rgb) scale = target_max / max(h, w) nw, nh = int(round(w * scale)), int(round(h * scale)) up = cv2.resize(img_rgb, (nw, nh), interpolation=cv2.INTER_LANCZOS4) if sharpen: blur = cv2.GaussianBlur(up, (0, 0), 1.2) up = cv2.addWeighted(up, 1.25, blur, -0.25, 0) return np.ascontiguousarray(up) def render_zoom_crop(img_rgb: np.ndarray, zoom_level: float, cx_norm: float = 0.5, cy_norm: float = 0.5) -> np.ndarray: """Return a crisp zoomed-in detail view around (cx_norm, cy_norm) at `zoom_level` (1.0 - 4.0x).""" if zoom_level <= 1.05: return img_rgb h, w = img_rgb.shape[:2] cw = max(64, int(round(w / zoom_level))) ch = max(64, int(round(h / zoom_level))) cx = int(round(cx_norm * w)) cy = int(round(cy_norm * h)) x0 = max(0, min(w - cw, cx - cw // 2)) y0 = max(0, min(h - ch, cy - ch // 2)) crop = img_rgb[y0 : y0 + ch, x0 : x0 + cw] return np.ascontiguousarray(cv2.resize(crop, (w, h), interpolation=cv2.INTER_LANCZOS4)) def draw_cm_ruler_grid(img_rgb: np.ndarray, width_cm: float, grid_n: int = 4) -> Tuple[np.ndarray, float, float, float]: """ Draws a clean real-world centimeter ruler border + 4x4 grid on the sketch so the painter can measure exact proportions on their physical canvas with a ruler! Returns: (annotated_img, height_cm, cell_w_cm, cell_h_cm) """ h, w = img_rgb.shape[:2] height_cm = round(width_cm * (h / max(w, 1)), 1) cell_w = round(width_cm / grid_n, 1) cell_h = round(height_cm / grid_n, 1) pad_top, pad_left = 30, 44 canvas = np.full((h + pad_top + 10, w + pad_left + 10, 3), 248, dtype=np.uint8) canvas[pad_top : pad_top + h, pad_left : pad_left + w] = img_rgb # Outer canvas border cv2.rectangle(canvas, (pad_left, pad_top), (pad_left + w - 1, pad_top + h - 1), (55, 65, 81), 2) # Crisp 4x4 proportion grid lines for i in range(1, grid_n): gx = pad_left + int(round(w * i / grid_n)) gy = pad_top + int(round(h * i / grid_n)) cv2.line(canvas, (gx, pad_top), (gx, pad_top + h - 1), (96, 150, 225), 1, cv2.LINE_AA) cv2.line(canvas, (pad_left, gy), (pad_left + w - 1, gy), (96, 150, 225), 1, cv2.LINE_AA) # Centimeter labels along top & left margins (ASCII-safe PIL bitmap font) pil_im = Image.fromarray(canvas) draw = ImageDraw.Draw(pil_im) for i in range(grid_n + 1): gx = pad_left + int(round(w * i / grid_n)) gy = pad_top + int(round(h * i / grid_n)) cm_x = round(width_cm * i / grid_n, 1) cm_y = round(height_cm * i / grid_n, 1) draw.text((max(2, gx - 14), 8), f"{cm_x:g}cm", fill=(30, 41, 59)) draw.text((4, max(pad_top - 4, gy - 6)), f"{cm_y:g}cm", fill=(30, 41, 59)) return np.ascontiguousarray(np.array(pil_im)), height_cm, cell_w, cell_h def make_smooth_sketch_animation(rough_rgb: np.ndarray, full_sketch_rgb: np.ndarray, width_cm: float) -> str: """ Smooth, accurate, non-dotted Pencil Sketching Animation GIF: Phase A (0-45%): Draws the centimeter grid & progressively reveals Stage 0 main continuous lines using a diagonal artist-hand sweep mask! Phase B (45-100%): Smoothly layers in Stage 1 full continuous details! """ h, w = rough_rgb.shape[:2] yy, xx = np.mgrid[0:h, 0:w].astype(np.float32) # Natural top-left to bottom-right diagonal drawing sweep sweep = (xx / max(w, 1)) * 0.55 + (yy / max(h, 1)) * 0.45 paper = np.full((h, w, 3), 250, dtype=np.uint8) frames: List[Image.Image] = [] durations: List[int] = [] bar_h = 30 def _pack(arr: np.ndarray, title: str, pct: int) -> Image.Image: grid_img, _, _, _ = draw_cm_ruler_grid(arr, width_cm, grid_n=4) gh, gw = grid_img.shape[:2] out = Image.new("RGB", (gw, gh + bar_h), (245, 240, 232)) out.paste(Image.fromarray(grid_img), (0, bar_h)) d = ImageDraw.Draw(out) d.text((10, 7), f"{title} ({pct}%)", fill=(30, 35, 48)) prog = int((gw - 20) * pct / 100) d.rectangle([10, bar_h - 5, gw - 10, bar_h - 2], fill=(220, 215, 205)) d.rectangle([10, bar_h - 5, 10 + prog, bar_h - 2], fill=(217, 119, 6)) return out # Phase A: Continuous reveal of Stage 0 main structural outlines for step in range(1, 9): t = step / 8.0 alpha = np.clip((t * 1.15 - sweep) * 5.0, 0.0, 1.0)[..., None] cur = np.clip(paper * (1.0 - alpha) + rough_rgb * alpha, 0, 255).astype(np.uint8) frames.append(_pack(cur, "1. Main Proportions & Outlines", int(t * 48))) durations.append(160) # Phase B: Continuous reveal of Stage 1 full details on top of Stage 0 for step in range(1, 9): t = step / 8.0 alpha = np.clip((t * 1.15 - sweep) * 5.0, 0.0, 1.0)[..., None] cur = np.clip(rough_rgb * (1.0 - alpha) + full_sketch_rgb * alpha, 0, 255).astype(np.uint8) frames.append(_pack(cur, "2. Refining Full Pencil Details", 48 + int(t * 52))) durations.append(170) # Hold final crisp sketch frames.append(_pack(full_sketch_rgb, "Complete Sketch Ready for Paint", 100)) durations.append(2200) tmp = tempfile.NamedTemporaryFile(suffix=".gif", delete=False) tmp.close() frames[0].save(tmp.name, save_all=True, append_images=frames[1:], duration=durations, loop=0, optimize=True) return tmp.name def make_timelapse_gif(stages_7: List[np.ndarray]) -> str: """Smooth cinematic 7-stage painting timelapse GIF with progress bar.""" labels = [ "Step 1/7: Main Outlines & Grid", "Step 2/7: Full Pencil Sketch", "Step 3/7: Sepia Underpainting", "Step 4/7: Broad Color Blocking", "Step 5/7: Shadows & 3D Volume", "Step 6/7: Mid-Details & Brushwork", "Step 7/7: Final Highlights", ] h, w = stages_7[0].shape[:2] bar_h = 32 def _annotate(arr: np.ndarray, text: str, prog_frac: float) -> Image.Image: canvas = Image.new("RGB", (w, h + bar_h), (245, 240, 232)) canvas.paste(Image.fromarray(arr), (0, bar_h)) d = ImageDraw.Draw(canvas) d.text((10, 7), text, fill=(30, 35, 48)) prog = int((w - 20) * prog_frac) d.rectangle([10, bar_h - 5, w - 10, bar_h - 2], fill=(220, 215, 205)) d.rectangle([10, bar_h - 5, 10 + prog, bar_h - 2], fill=(79, 70, 229)) return canvas frames: List[Image.Image] = [] durations: List[int] = [] n = len(stages_7) for i, img in enumerate(stages_7): frames.append(_annotate(img, labels[i], (i + 1) / n)) durations.append(1100 if i < n - 1 else 2400) if i < n - 1: nxt = stages_7[i + 1] for alpha in (0.25, 0.50, 0.75): blend = cv2.addWeighted(img, 1.0 - alpha, nxt, alpha, 0) frames.append(_annotate(blend, labels[i + 1], (i + 1 + alpha) / n)) durations.append(85) tmp = tempfile.NamedTemporaryFile(suffix=".gif", delete=False) tmp.close() frames[0].save(tmp.name, save_all=True, append_images=frames[1:], duration=durations, loop=0, optimize=True) return tmp.name def make_clear_paint_zones(prev_img: np.ndarray, curr_img: np.ndarray) -> np.ndarray: diff = np.mean(np.abs(curr_img.astype(np.float32) - prev_img.astype(np.float32)), axis=-1) diff = cv2.GaussianBlur(diff, (7, 7), 0) thr = max(9.0, float(np.percentile(diff, 68))) bin_mask = (diff >= thr).astype(np.uint8) * 255 bin_mask = cv2.morphologyEx(bin_mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8)) soft = cv2.GaussianBlur(bin_mask.astype(np.float32) / 255.0, (9, 9), 0)[..., None] gray_bg = cv2.cvtColor(cv2.cvtColor(curr_img, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB).astype(np.float32) * 0.35 + 162.0 blended = np.ascontiguousarray(np.clip(gray_bg * (1.0 - soft) + curr_img.astype(np.float32) * soft, 0, 255).astype(np.uint8)) contours, _ = cv2.findContours(bin_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(blended, contours, -1, (234, 88, 12), 2, cv2.LINE_AA) return blended def make_value_study_3tone(img_rgb: np.ndarray) -> np.ndarray: gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY) gray = cv2.bilateralFilter(gray, 9, 55, 55) t1, t2 = np.percentile(gray, [33, 72]) out = np.full_like(gray, 138) out[gray <= t1] = 28 out[gray >= t2] = 242 return cv2.cvtColor(out, cv2.COLOR_GRAY2RGB) def make_attention_overlay(img_rgb: np.ndarray, focal_01: np.ndarray) -> np.ndarray: heat_u8 = np.clip(focal_01 * 255.0, 0, 255).astype(np.uint8) heat_u8 = cv2.GaussianBlur(heat_u8, (15, 15), 0) heat_bgr = cv2.applyColorMap(heat_u8, cv2.COLORMAP_INFERNO) heat_rgb = cv2.cvtColor(heat_bgr, cv2.COLOR_BGR2RGB) return cv2.addWeighted(img_rgb, 0.50, heat_rgb, 0.50, 0) def render_aesthetic_score_html(score_10: float, width_cm: float, height_cm: float, cell_w: float, cell_h: float) -> str: pct = int(round(np.clip(score_10 * 10.0, 5, 100))) if score_10 >= 8.0: tier = "شاهکار و بسیار چشم‌گیر (جزو آثار برتر)" bar_col = "#16a34a" elif score_10 >= 6.5: tier = "جذابیت بصری بالا و ترکیب‌بندی قوی" bar_col = "#d97706" else: tier = "متعادل و آرام (مناسب تمرین آماتور)" bar_col = "#4f46e5" return f"""
امتیاز جذابیت و خیرگی بصری (آموزش‌دیده توسط PaintPathNet v2 روی ۵,۶۰۹ اثر)
⭐ {score_10:.1f} / 10 — {tier}
📐 ابعاد واقعی بوم و شبکه پیشنهادی
بوم: {width_cm:g} × {height_cm:g} cm  |  هر خانه شبکه: {cell_w:g} × {cell_h:g} cm
""" def highlight_target_rgb_on_canvas(img_rgb: np.ndarray, target_rgb: Tuple[int, int, int], tolerance: float = 25.0) -> Tuple[np.ndarray, str]: img_lab = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2LAB).astype(np.float32) t_lab = cv2.cvtColor(np.array([[target_rgb]], dtype=np.uint8), cv2.COLOR_RGB2LAB).astype(np.float32)[0, 0] dist = np.linalg.norm(img_lab - t_lab[None, None, :], axis=-1) mask = np.clip(1.0 - (dist - tolerance * 0.5) / max(tolerance, 1.0), 0.0, 1.0) mask_u8 = (mask > 0.45).astype(np.uint8) * 255 soft = cv2.GaussianBlur(mask.astype(np.float32), (7, 7), 0)[..., None] bg = cv2.cvtColor(cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB).astype(np.float32) * 0.24 + 190.0 out = np.ascontiguousarray(np.clip(bg * (1.0 - soft) + img_rgb.astype(np.float32) * soft, 0, 255).astype(np.uint8)) contours, _ = cv2.findContours(mask_u8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(out, contours, -1, (220, 38, 38), 1, cv2.LINE_AA) r, g, b = target_rgb hex_code = f"#{r:02X}{g:02X}{b:02X}" recipe = solve_tube_recipe(target_rgb) bars_html = "" for name, pct in recipe: tr, tg, tb = ARTIST_TUBES[name] fa_name = TUBE_PERSIAN.get(name, name) bars_html += f"""
🎨 {fa_name} ({name}) {pct}%
""" card_html = f"""
رنگ انتخاب‌شده: {hex_code}
RGB({r}, {g}, {b}) — کادرهای قرمز در تصویر دقیقاً تمام نقاطی هستند که باید این رنگ را بزنی!
🧪 دستور ترکیب واقعی رنگ‌های تیوپی (Kubelka-Munk):
{bars_html}
""" return out, card_html def render_palette_card(palette: List[PaletteColor]) -> np.ndarray: card_w, row_h = 720, 50 im = Image.new("RGB", (card_w, 42 + len(palette) * row_h), (252, 250, 246)) draw = ImageDraw.Draw(im) draw.text((16, 12), "Master Palette - Physical Paint-Tube Mixing Recipes", fill=(30, 30, 35)) for i, c in enumerate(palette): y0 = 38 + i * row_h draw.rectangle([16, y0 + 5, 80, y0 + row_h - 5], fill=c.rgb, outline=(60, 60, 60), width=1) recipe_str = " + ".join(f"{pct}% {name}" for name, pct in c.mixing_recipe) draw.text((94, y0 + 6), f"#{c.index + 1} {c.hex} ({c.proportion * 100:.1f}%)", fill=(25, 25, 25)) draw.text((94, y0 + 25), f"Mix: {recipe_str}", fill=(75, 75, 80)) return np.array(im) def evaluate_amateur_painting(ref_img: np.ndarray, user_img: np.ndarray) -> Tuple[Optional[np.ndarray], str]: if ref_img is None or user_img is None: return None, "لطفاً هم نقاشی اصلی (بالای صفحه) و هم عکس نقاشیِ دستِ خودت را آپلود کن." ref = cv2.resize(auto_crop_borders(ref_img), (384, 384), interpolation=cv2.INTER_AREA) usr = cv2.resize(auto_crop_borders(user_img), (384, 384), interpolation=cv2.INTER_AREA) ref_lab = cv2.cvtColor(ref, cv2.COLOR_RGB2LAB).astype(np.float32) usr_lab = cv2.cvtColor(usr, cv2.COLOR_RGB2LAB).astype(np.float32) delta_e = np.linalg.norm(ref_lab - usr_lab, axis=-1) color_score = float(np.clip(100.0 - delta_e.mean() * 1.4, 0, 100)) ref_l, usr_l = ref_lab[..., 0], usr_lab[..., 0] val_diff = usr_l.mean() - ref_l.mean() value_score = float(np.clip(100.0 - np.abs(ref_l - usr_l).mean() * 1.8, 0, 100)) r_g = cv2.GaussianBlur(cv2.cvtColor(ref, cv2.COLOR_RGB2GRAY).astype(np.float32), (5, 5), 0) u_g = cv2.GaussianBlur(cv2.cvtColor(usr, cv2.COLOR_RGB2GRAY).astype(np.float32), (5, 5), 0) r_e = np.hypot(cv2.Sobel(r_g, cv2.CV_32F, 1, 0), cv2.Sobel(r_g, cv2.CV_32F, 0, 1)) u_e = np.hypot(cv2.Sobel(u_g, cv2.CV_32F, 1, 0), cv2.Sobel(u_g, cv2.CV_32F, 0, 1)) corr = float(np.corrcoef(r_e.flatten(), u_e.flatten())[0, 1]) if r_e.std() > 0 and u_e.std() > 0 else 0.0 struct_score = float(np.clip((corr + 0.2) * 85.0, 0, 100)) overall = 0.40 * color_score + 0.35 * value_score + 0.25 * struct_score err_blur = cv2.GaussianBlur((np.clip(delta_e / 55.0, 0, 1) * 255).astype(np.uint8), (15, 15), 0) heat = cv2.cvtColor(cv2.applyColorMap(err_blur, cv2.COLORMAP_JET), cv2.COLOR_BGR2RGB) overlay = cv2.addWeighted(usr, 0.58, heat, 0.42, 0) tips = [] if val_diff > 10: tips.append("- **سایه‌ها کمی روشن‌اند:** روی نواحی قرمز، سایه‌ها را با کمی قهوه‌ای سوخته (Burnt Umber) عمیق‌تر کن.") elif val_diff < -10: tips.append("- **نقاشی کمی تیره شده:** در بخش‌های روشن کمی سفید تیتانیوم اضافه کن.") else: tips.append("- **تعادل نور و سایه عالی است!**") if color_score < 65: tips.append("- **دقت رنگ:** در تب «قطره‌چکان ساخت رنگ» روی بخش‌های قرمز کلیک کن تا فرمول ترکیبش را ببینی.") if struct_score < 55: tips.append("- **تناسبات:** با خط‌کش سانتی‌متری اسلاید ۱ جای اصلی اشیا را چک کن.") report = ( f"### 🏆 امتیاز کلی کار دست تو: **{overall:.1f} / 100**\n" f"- دقت رنگ‌ها: `{color_score:.1f}` | تعادل نور و سایه: `{value_score:.1f}` | تناسبات: `{struct_score:.1f}`\n\n" f"#### 💡 توصیه‌های مربی (قرمز = نیاز به اصلاح، آبی = عالی):\n" + "\n".join(tips) ) return overlay, report # ============================================================ # 3. 7-Step Pedagogical Curriculum & Model Loading # ============================================================ HERE = Path(__file__).resolve().parent DEFAULT_HF_REPO = "tarfandoon/paintpath-net-v2" ON_SPACES = bool(os.environ.get("SPACE_ID")) MODEL = None def _img_to_b64_jpeg(img_rgb: np.ndarray, max_side: int = 768, quality: int = 85) -> str: h, w = img_rgb.shape[:2] scale = min(1.0, max_side / max(h, w)) if scale < 1.0: img_rgb = cv2.resize(img_rgb, (int(round(w * scale)), int(round(h * scale))), interpolation=cv2.INTER_AREA) buf = io.BytesIO() Image.fromarray(img_rgb).save(buf, format="JPEG", quality=quality) return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii") def build_ar_camera_html(rough_rgb: np.ndarray, sketch_rgb: np.ndarray, block_rgb: np.ndarray, final_rgb: np.ndarray) -> str: """ 60-FPS Browser-Native AR Canvas Tracing Studio (Phone Back Camera & Laptop Webcam)! Uses CSS `mix-blend-mode: multiply` so white paper becomes 100% transparent and ONLY the crisp pencil lines float directly over the user's real paper/canvas. """ b64_rough = _img_to_b64_jpeg(rough_rgb) b64_sketch = _img_to_b64_jpeg(sketch_rgb) b64_block = _img_to_b64_jpeg(block_rgb) b64_final = _img_to_b64_jpeg(final_rgb) inner_doc = f"""
AR Sketch Overlay
دکمه «📷 روشن کردن دوربین» را بزن، گوشی را روی پایه بگذار و با انگشت یا ماوس طرح را روی کاغذ واقعی تنظیم کن!
""" escaped = html_lib.escape(inner_doc, quote=True) return ( f'' ) def build_step_guides(width_cm: float, height_cm: float, cell_w: float, cell_h: float) -> Dict[int, str]: return { 1: ( f"### 📐 گام ۱ از ۷ — کادربندی به سانتی‌متر و خطوط اصلی *(مداد HB، خیلی کم‌رنگ)*\n" f"- **ابعاد بوم پیشنهادی:** `{width_cm:g} × {height_cm:g} cm` — روی بومت یک شبکه **4×4** با خانه‌های **`{cell_w:g} × {cell_h:g} cm`** بکش.\n" f"- فقط خطوط پیوسته و اصلی تصویر را داخل هر خانه منتقل کن تا تناسبات ۱۰۰٪ دقیق شود." ), 2: ( f"### ✏️ گام ۲ از ۷ — اسکچ کامل مدادی *(مداد 2B)*\n" f"- با کمک انیمیشن اسکچ سمت چپ، تمام جزئیات و فرم‌های اصلی را روی طرح گام ۱ کامل کن.\n" f"- خطوط اضافه شبکه را بعد از اطمینان از تناسبات با پاک‌کن خمیری کمرنگ کن." ), 3: ( "### 🤎 گام ۳ از ۷ — زیررنگ‌گذاری تک‌رنگ سپیا *(قلم تخت پهن #14 — حدود ۲.۵ سانتی‌متر)*\n" "- یک تکنیک اصیل استادان رنگ‌روغن! فقط با **قهوه‌ای سوخته (Burnt Umber) + کمی سفید**، سایه‌ها و تیرگی‌های اصلی را خیلی رقیق روی بوم بگذار تا حجم کار دربیاید." ), 4: ( "### 🖌️ گام ۴ از ۷ — رنگ‌گذاری پایه و لکه‌های بزرگ *(قلم تخت #12 — حدود ۲ سانتی‌متر)*\n" "- از تب **قطره‌چکان ساخت رنگ**، رنگ هر ناحیه بزرگ را بساز و کل بوم را با لکه‌های ساده و تخت پر کن (فعلاً سراغ جزئیات ریز نرو)." ), 5: ( "### 🌗 گام ۵ از ۷ — سایه‌ها و حجم سه‌بعدی *(قلم متوسط #8 — حدود ۱ سانتی‌متر)*\n" "- تیک **«📍 نشان بده کجا را رنگ کنم»** را بزن! نواحی دارای کادر نارنجی دقیقاً جاهایی هستند که باید سایه‌های عمیق‌تر و حجم اضافه کنی." ), 6: ( "### ✨ گام ۶ از ۷ — جزئیات میانی و بافت قلم‌مو *(قلم گرد #3 — حدود ۴ میلی‌متر)*\n" "- لبه‌های مهم را تمیز کن، بافت اشیا را بکش و انتقال بین رنگ‌های کنار هم را با قلم نرم محو کن." ), 7: ( "### 🌟 گام ۷ از ۷ — هایلایت‌ها و ضربه‌های نهایی *(قلم ریز #0-#1 — ۱ تا ۲ میلی‌متر)*\n" "- با رنگ غلیظ و روشن، آخرین نقطه‌های نور و کنتراست تیز (نواحی کادر نارنجی) را بزن تا نقاشی زنده و تمام شود!" ), } def load_paintpath_model(model_dir: str = "", ckpt_path: str = "", hf_repo: str = ""): global MODEL token = os.environ.get("HF_TOKEN") or None init_dev = torch.device("cpu") if ON_SPACES else torch.device("cuda" if torch.cuda.is_available() else "cpu") if model_dir and Path(model_dir).exists() and (Path(model_dir) / "config.json").exists(): MODEL = PaintPathNetV2.from_pretrained(model_dir, pretrained=False).to(init_dev).eval() return repo = hf_repo or DEFAULT_HF_REPO if repo: MODEL = PaintPathNetV2.from_pretrained(repo, pretrained=False, token=token).to(init_dev).eval() return if ckpt_path and Path(ckpt_path).exists(): m = PaintPathNetV2(pretrained=False).to(init_dev) ckpt = torch.load(ckpt_path, map_location=init_dev) m.load_state_dict(ckpt["model"] if "model" in ckpt else ckpt) MODEL = m.eval() def _gpu_decorator(fn): if spaces is not None and ON_SPACES: return spaces.GPU(fn) return fn @_gpu_decorator @torch.no_grad() def run_paintpath_studio(input_img: np.ndarray, width_cm: float, num_colors: int): if input_img is None or MODEL is None: return None, "", None, None, None, "لطفاً ابتدا یک نقاشی آپلود کن.", 1, 1.0, [], None, None, None, "", gr.update(), None, None, "" dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") MODEL.to(dev) clean = auto_crop_borders(input_img) h, w = clean.shape[:2] # Keep true high-res ~1024px original for crisp fullscreen & zooming hi_scale = min(1.0, 1024.0 / max(h, w)) orig_hi = cv2.resize(clean, (int(round(w * hi_scale)), int(round(h * hi_scale))), interpolation=cv2.INTER_AREA) scale = 512.0 / max(h, w) nw = max(64, (int(round(w * scale)) // 32) * 32) nh = max(64, (int(round(h * scale)) // 32) * 32) resized = cv2.resize(clean, (nw, nh), interpolation=cv2.INTER_AREA) inp = torch.from_numpy(resized).permute(2, 0, 1).unsqueeze(0).float().to(dev) / 255.0 gpu_name = torch.cuda.get_device_name(0) if dev.type == "cuda" else "" use_amp = (dev.type == "cuda") and ("1650" not in gpu_name and "1660" not in gpu_name) # Run all 6 native PaintPathNetV2 stages + Real Aesthetic Score + Deep Focal Map! stages_v2 = [] aes_val = 7.5 with torch.amp.autocast("cuda", enabled=use_amp, dtype=torch.float16): focal_t = MODEL.extract_focal_map(inp) for s_idx in range(6): st = torch.tensor([s_idx], dtype=torch.long, device=dev) pred, aes = MODEL(inp, st) if s_idx == 0: aes_val = float(aes[0].float().clamp(0, 1).item()) * 10.0 arr = np.ascontiguousarray((pred[0].float().clamp(0, 1).permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8)) stages_v2.append(arr) focal_01 = focal_t[0, 0].float().cpu().numpy() m_rough = polish_continuous_sketch(stages_v2[0]) m_sketch = polish_continuous_sketch(stages_v2[1]) m_sepia = stages_v2[2] m_block = stages_v2[3] m_shadow = stages_v2[4] m_detail = stages_v2[5] # Smooth animations at fast 512px sketch_gif = make_smooth_sketch_animation(m_rough, m_sketch, float(width_cm)) timelapse_gif = make_timelapse_gif([m_rough, m_sketch, m_sepia, m_block, m_shadow, m_detail, resized]) # Upscale ALL interactive display stages to crisp 1024px so Maximize & Zoom are razor-sharp! hi_rough = upscale_hi_res(m_rough, 1024, sharpen=True) hi_sketch = upscale_hi_res(m_sketch, 1024, sharpen=True) hi_sepia = upscale_hi_res(m_sepia, 1024, sharpen=False) hi_block = upscale_hi_res(m_block, 1024, sharpen=False) hi_shadow = upscale_hi_res(m_shadow, 1024, sharpen=True) hi_detail = upscale_hi_res(m_detail, 1024, sharpen=True) hi_final = cv2.resize(orig_hi, (hi_detail.shape[1], hi_detail.shape[0]), interpolation=cv2.INTER_LANCZOS4) # Render centimeter ruler & 4x4 grid AT 1024px for ultra-sharp readable numbers! st1_cm, height_cm, cell_w, cell_h = draw_cm_ruler_grid(hi_rough, float(width_cm), grid_n=4) st2_cm, _, _, _ = draw_cm_ruler_grid(hi_sketch, float(width_cm), grid_n=4) guides = build_step_guides(float(width_cm), height_cm, cell_w, cell_h) score_html = render_aesthetic_score_html(aes_val, float(width_cm), height_cm, cell_w, cell_h) step_imgs = {1: st1_cm, 2: st2_cm, 3: hi_sepia, 4: hi_block, 5: hi_shadow, 6: hi_detail, 7: hi_final} blank_hi = np.full_like(hi_final, 248) paint_zones = { 1: st1_cm, 2: st2_cm, 3: make_clear_paint_zones(blank_hi, hi_sepia), 4: make_clear_paint_zones(hi_sepia, hi_block), 5: make_clear_paint_zones(hi_block, hi_shadow), 6: make_clear_paint_zones(hi_shadow, hi_detail), 7: make_clear_paint_zones(hi_detail, hi_final), } gallery_items = [ (st1_cm, "۱. کادر و خطوط اصلی (cm)"), (st2_cm, "۲. اسکچ کامل مدادی"), (hi_sepia, "۳. زیررنگ سپیا"), (hi_block, "۴. رنگ‌گذاری پایه"), (hi_shadow, "۵. سایه‌ها و حجم"), (hi_detail, "۶. جزئیات میانی"), (hi_final, "۷. نقاشی نهایی"), ] palette = extract_physical_palette(resized, k=int(num_colors)) pal_card = render_palette_card(palette) loc_img, loc_html = highlight_target_rgb_on_canvas(hi_final, palette[0].rgb) color_choices = [f"رنگ #{c.index + 1} ({c.hex}) — {c.proportion * 100:.1f}%" for c in palette] focal_hi = cv2.resize(focal_01, (hi_final.shape[1], hi_final.shape[0]), interpolation=cv2.INTER_LINEAR) attention_img = make_attention_overlay(hi_final, focal_hi) value_study = make_value_study_3tone(hi_final) ar_html = build_ar_camera_html(m_rough, m_sketch, m_block, resized) state = { "resized": hi_final, "step_imgs": step_imgs, "paint_zones": paint_zones, "guides": guides, "palette": palette, "zoom_cx": 0.5, "zoom_cy": 0.5, } return ( state, score_html, sketch_gif, timelapse_gif, step_imgs[1], guides[1], 1, 1.0, gallery_items, hi_final, pal_card, loc_img, loc_html, gr.update(choices=color_choices, value=color_choices[0]), attention_img, value_study, ar_html, ) def render_slide(step_num: int, show_zones: bool, zoom_level: float, state: Optional[dict]): if not state: return None, "ابتدا یک نقاشی آپلود کن.", 1 s = max(1, min(7, int(step_num))) base = state["paint_zones"][s] if show_zones else state["step_imgs"][s] zoomed = render_zoom_crop(base, float(zoom_level), state.get("zoom_cx", 0.5), state.get("zoom_cy", 0.5)) return zoomed, state["guides"][s], s def prev_slide(step_num: int, show_zones: bool, zoom_level: float, state: Optional[dict]): return render_slide(max(1, int(step_num) - 1), show_zones, zoom_level, state) def next_slide(step_num: int, show_zones: bool, zoom_level: float, state: Optional[dict]): return render_slide(min(7, int(step_num) + 1), show_zones, zoom_level, state) def on_slide_click_zoom(step_num: int, show_zones: bool, zoom_level: float, state: Optional[dict], evt: gr.SelectData): """Click anywhere on the slide to center the zoom lens right on that detail!""" if not state: return None, "ابتدا یک نقاشی آپلود کن.", 1, 1.0 s = max(1, min(7, int(step_num))) base = state["paint_zones"][s] if show_zones else state["step_imgs"][s] h, w = base.shape[:2] # If currently at 1x, clicking auto-zooms to 2.5x right where clicked; otherwise re-centers zoom new_zoom = 2.5 if float(zoom_level) <= 1.05 else float(zoom_level) state["zoom_cx"] = float(np.clip(evt.index[0] / max(w, 1), 0.0, 1.0)) state["zoom_cy"] = float(np.clip(evt.index[1] / max(h, 1), 0.0, 1.0)) zoomed = render_zoom_crop(base, new_zoom, state["zoom_cx"], state["zoom_cy"]) return zoomed, state["guides"][s], s, new_zoom def on_color_dropdown(color_label: str, state: Optional[dict]): if not state or not color_label: return None, "" try: idx = int(color_label.split("#")[1].split(" ")[0]) - 1 except Exception: idx = 0 idx = max(0, min(idx, len(state["palette"]) - 1)) return highlight_target_rgb_on_canvas(state["resized"], state["palette"][idx].rgb) def on_canvas_click(state: Optional[dict], evt: gr.SelectData): if not state: return None, "

ابتدا نقاشی را تحلیل کن.

" img = state["resized"] x, y = int(evt.index[0]), int(evt.index[1]) h, w = img.shape[:2] x, y = max(0, min(x, w - 1)), max(0, min(y, h - 1)) patch = img[max(0, y - 2) : min(h, y + 3), max(0, x - 2) : min(w, x + 3)] mean_rgb = tuple(int(round(v)) for v in patch.reshape(-1, 3).mean(axis=0)) return highlight_target_rgb_on_canvas(img, mean_rgb, tolerance=24.0) # ============================================================ # 4. Crisp, High-Contrast Flagship UI (Light & Dark Mode Safe) # ============================================================ CUSTOM_CSS = """ .studio-hero { background: linear-gradient(135deg, #fff9ef 0%, #fef2dc 50%, #eef2ff 100%) !important; border: 2px solid #e5d1b3 !important; border-radius: 22px !important; padding: 26px 30px !important; margin-bottom: 18px !important; text-align: center !important; box-shadow: 0 10px 28px rgba(15, 23, 42, 0.06) !important; } .studio-hero h1 { margin: 0 0 8px 0 !important; font-size: 2.1rem !important; font-weight: 900 !important; color: #111827 !important; } .studio-hero p { margin: 0 auto 16px auto !important; max-width: 780px !important; font-size: 1.04rem !important; font-weight: 500 !important; color: #374151 !important; } .brand-links { display: flex !important; justify-content: center !important; flex-wrap: wrap !important; gap: 10px !important; } .brand-links a { display: inline-flex !important; align-items: center !important; gap: 6px !important; padding: 8px 16px !important; border-radius: 999px !important; background: #1f2937 !important; color: #ffffff !important; text-decoration: none !important; font-size: 0.88rem !important; font-weight: 700 !important; } .brand-links a:hover { background: #d97706 !important; color: #ffffff !important; } .studio-footer { text-align: center !important; margin-top: 26px !important; padding: 16px !important; background: #fff9ef !important; border: 1px solid #e5d1b3 !important; border-radius: 14px !important; color: #1f2937 !important; font-size: 0.94rem !important; font-weight: 600 !important; } .studio-footer a { color: #b45309 !important; text-decoration: none !important; font-weight: 800 !important; } """ def build_ui(): with gr.Blocks(title="PaintPath Studio v2 — Ali Jahani") as demo: studio_state = gr.State(value=None) gr.HTML( """

🎨 PaintPath Studio v2 — هوش مصنوعی مربی نقاشی تو

همیشه انسان کار را برای هوش مصنوعی ساده می‌کند؛ این بار هوش مصنوعی نقاشی را با خط‌کش واقعی به سانتی‌متر، انیمیشن اسکچ، ۷ مرحله آموزشی و فرمول ساخت رنگ ساده می‌کند تا تو نقاش بشوی!

""" ) # Clean Upload + Canvas Size Bar with gr.Row(equal_height=True): with gr.Column(scale=2): in_img = gr.Image(type="numpy", label="۱. نقاشی مورد نظرت را اینجا آپلود کن", height=270) with gr.Column(scale=1): gr.Markdown("### 📐 تنظیم بوم واقعی و شروع") width_cm = gr.Slider(15, 100, value=40, step=5, label="عرض بوم واقعی تو (سانتی‌متر)") num_colors = gr.Slider(6, 12, value=8, step=1, label="تعداد رنگ‌های پالت اصلی") run_btn = gr.Button("✨ ساخت نقشه ۷ مرحله‌ای + تحلیل کامل", variant="primary", size="lg") score_banner = gr.HTML("") with gr.Tabs(): # TAB 1: Interactive 7-Stage Slides + Smooth Animations with gr.Tab("🎬 ۱. آموزش ۷ مرحله‌ای + انیمیشن اسکچ و فیلم"): with gr.Row(): with gr.Column(scale=2): gr.Markdown("### 🖼️ اسلاید تعاملی ۷ مرحله‌ای (کیفیت بالا 1024px — برای زوم روی هر نقطه کلیک کن!)") slide_img = gr.Image(label="بوم هدف (کلیک روی تصویر = زوم روی جزئیات | آیکون فول‌اسکرین = تمام‌صفحه HD)", height=540, interactive=False) with gr.Row(): prev_btn = gr.Button("⬅️ مرحله قبل") next_btn = gr.Button("مرحله بعد ➡️", variant="primary") reset_zoom_btn = gr.Button("🔍 ریست زوم (1×)") with gr.Row(): step_slider = gr.Slider(1, 7, value=1, step=1, label="شماره مرحله (۱ تا ۷)") zoom_slider = gr.Slider(1.0, 4.0, value=1.0, step=0.25, label="🔍 بزرگ‌نمایی / زوم (1× تا 4×)") zone_chk = gr.Checkbox(value=False, label="📍 نشان بده در این مرحله کجا را رنگ کنم!") slide_guide = gr.Markdown("پس از آپلود نقاشی، اینجا راهنمای دقیق هر مرحله (با سایز قلم‌مو و ابعاد بوم به سانتی‌متر) نمایش داده می‌شود.") with gr.Column(scale=1): gr.Markdown("### ✏️ انیمیشن روان اسکچ کشیدن (خطوط پیوسته)") sketch_gif_out = gr.Image(label="ترسیم مرحله‌به‌مرحله خطوط اصلی و جزئیات", interactive=False) gr.Markdown("### 🎥 فیلم تایم‌لپس کامل ۷ مرحله‌ای") timelapse_out = gr.Image(label="سفر کامل از خطوط اولیه تا نقاشی نهایی", interactive=False) gr.Markdown("#### 🗺️ نمای یکپارچه هر ۷ مرحله کنار هم:") gallery_out = gr.Gallery(columns=7, height=190, label="مسیر کامل نقاشی") # TAB 2: Interactive Click-to-Extract Color Mixer & Canvas Locator with gr.Tab("🎨 ۲. قطره‌چکان ساخت رنگ تعاملی (کلیک روی نقاشی!)"): gr.Markdown("### 💧 روی هر نقطه‌ای از نقاشی سمت چپ کلیک کن تا **فرمول دقیق ترکیب رنگ تیوپی‌اش** و **تمام جاهایی که آن رنگ روی بوم هست** را ببینی!") with gr.Row(): clickable_img = gr.Image(label="👆 روی هر نقطه نقاشی کلیک کن", interactive=False) color_loc_img = gr.Image(label="📍 تمام نقاطی که باید این رنگ را بزنی (کادر قرمز)", interactive=False) with gr.Row(): with gr.Column(scale=1): color_dropdown = gr.Dropdown(choices=[], label="یا از رنگ‌های اصلی پالت انتخاب کن:", interactive=True) color_recipe_html = gr.HTML("
روی هر نقطه‌ای از نقاشی کلیک کن تا دستور ساخت رنگش را ببینی.
") with gr.Column(scale=1): pal_out = gr.Image(label="کارت کامل پالت رنگ فیزیکی") # TAB 3: Dedicated Eye Attention, Aesthetic Score & Value Study with gr.Tab("👁️ ۳. کانون توجه چشم و نورپردازی"): gr.Markdown( "### 🔥 نگاهِ مغز هوش مصنوعی به نقاشی\n" "مدل **`PaintPathNet v2`** نشان می‌دهد **چشم مخاطب اول به کجا خیره می‌شود** (نواحی زرد و قرمز) و در کنارش **مطالعه ۳ سطحی نور و سایه** را می‌دهد." ) with gr.Row(): attn_out = gr.Image(label="🔥 نقشه کانون توجه چشم (ConvNeXt Deep Focal Map)") val_out = gr.Image(label="🌗 مطالعه ارزش نوری ۳ سطحی (تیره / میانی / روشن)") # TAB 4: AR Live Camera Tracing (Phone Back Camera & Laptop Webcam!) with gr.Tab("📱 ۴. دوربین AR (کشیدن مستقیم روی کاغذ واقعی!)"): gr.Markdown( "### 📷 حالت واقعیت افزوده (AR Canvas Tracing) — بدون نیاز به اپلیکیشن!\n" "دوربین گوشی (یا وبکم) را روشن کن، پس‌زمینه سفید اسکچ **خودکار حذف می‌شود** و فقط خطوط مدادی روی تصویر زنده کاغذت می‌افتند — گوشی را روی پایه بگذار و مستقیم با مداد روی کاغذ واقعی بکش!" ) ar_camera_out = gr.HTML( "
ابتدا در بالای صفحه یک نقاشی آپلود کن و دکمه «✨ ساخت نقشه ۷ مرحله‌ای» را بزن تا دوربین AR فعال شود!
" ) # TAB 5: Check My Hand-Painted Canvas with gr.Tab("🏆 ۵. ارزیابی نقاشیِ دستِ تو"): gr.Markdown("از نقاشی‌ای که خودت با دست روی بوم یا کاغذ کشیدی عکس بگیر و اینجا آپلود کن تا **امتیاز ۰ تا ۱۰۰ و نقشه اصلاح** بگیری!") with gr.Row(): user_canvas_in = gr.Image(type="numpy", label="📸 عکس نقاشیِ دستِ خودت") feedback_img_out = gr.Image(label="🔍 نقشه اصلاح (قرمز = نیاز به اصلاح، آبی = عالی)") check_btn = gr.Button("✨ ارزیابی نقاشی من", variant="primary") feedback_md_out = gr.Markdown("") gr.HTML( """ """ ) # Events run_btn.click( fn=run_paintpath_studio, inputs=[in_img, width_cm, num_colors], outputs=[ studio_state, score_banner, sketch_gif_out, timelapse_out, slide_img, slide_guide, step_slider, zoom_slider, gallery_out, clickable_img, pal_out, color_loc_img, color_recipe_html, color_dropdown, attn_out, val_out, ar_camera_out, ], ) step_slider.change(render_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider]) zone_chk.change(render_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider]) zoom_slider.change(render_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider]) prev_btn.click(prev_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider]) next_btn.click(next_slide, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider]) slide_img.select(on_slide_click_zoom, [step_slider, zone_chk, zoom_slider, studio_state], [slide_img, slide_guide, step_slider, zoom_slider]) reset_zoom_btn.click(lambda s, z, st: (*render_slide(s, z, 1.0, st), 1.0), [step_slider, zone_chk, studio_state], [slide_img, slide_guide, step_slider, zoom_slider]) color_dropdown.change(on_color_dropdown, [color_dropdown, studio_state], [color_loc_img, color_recipe_html]) clickable_img.select(on_canvas_click, [studio_state], [color_loc_img, color_recipe_html]) check_btn.click(evaluate_amateur_painting, [in_img, user_canvas_in], [feedback_img_out, feedback_md_out]) return demo if ON_SPACES: load_paintpath_model( model_dir=str(HERE / "hf_model"), hf_repo=os.environ.get("HF_MODEL_REPO", DEFAULT_HF_REPO), ) demo = build_ui() demo.launch(theme=gr.themes.Soft(), css=CUSTOM_CSS) elif __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--model-dir", type=str, default=str(HERE / "hf_model")) parser.add_argument("--ckpt", type=str, default="") parser.add_argument("--hf-repo", type=str, default=os.environ.get("HF_MODEL_REPO", DEFAULT_HF_REPO)) parser.add_argument("--port", type=int, default=7861) args = parser.parse_args() load_paintpath_model(args.model_dir, args.ckpt, args.hf_repo) demo = build_ui() demo.launch(server_name="127.0.0.1", server_port=args.port, inbrowser=True, theme=gr.themes.Soft(), css=CUSTOM_CSS)