Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
hf_space/app.py — PaintPath Studio by Ali Jahani
|
| 3 |
100% Self-Contained Hugging Face Space & Local Runner.
|
| 4 |
|
| 5 |
Model : https://huggingface.co/tarfandoon/paintpath-net
|
|
@@ -147,7 +147,7 @@ class PaintPathNet(nn.Module, PyTorchModelHubMixin):
|
|
| 147 |
|
| 148 |
|
| 149 |
# ============================================================
|
| 150 |
-
# 2. Physical Pigment
|
| 151 |
# ============================================================
|
| 152 |
ARTIST_TUBES: Dict[str, Tuple[int, int, int]] = {
|
| 153 |
"Titanium White": (245, 245, 242),
|
|
@@ -160,6 +160,17 @@ ARTIST_TUBES: Dict[str, Tuple[int, int, int]] = {
|
|
| 160 |
"Viridian Green": (34, 118, 88),
|
| 161 |
}
|
| 162 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
def _srgb_to_linear(rgb01: np.ndarray) -> np.ndarray:
|
| 165 |
return np.where(rgb01 <= 0.04045, rgb01 / 12.92, ((rgb01 + 0.055) / 1.055) ** 2.4)
|
|
@@ -253,122 +264,230 @@ def add_proportion_grid(img_rgb: np.ndarray, grid_n: int = 4) -> np.ndarray:
|
|
| 253 |
out = img_rgb.copy()
|
| 254 |
h, w = out.shape[:2]
|
| 255 |
for i in range(1, grid_n):
|
| 256 |
-
cv2.line(out, (0, int(round(h * i / grid_n))), (w, int(round(h * i / grid_n))), (
|
| 257 |
-
cv2.line(out, (int(round(w * i / grid_n)), 0), (int(round(w * i / grid_n)), h), (
|
| 258 |
return out
|
| 259 |
|
| 260 |
|
| 261 |
-
def
|
| 262 |
-
|
| 263 |
-
gray = cv2.
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
mask = np.clip((diff - thr * 0.45) / max(thr * 1.4, 1.0), 0.0, 1.0)[..., None]
|
| 284 |
-
dimmed = curr_img.astype(np.float32) * 0.22 + 28.0
|
| 285 |
-
blended = dimmed * (1.0 - mask) + curr_img.astype(np.float32) * mask
|
| 286 |
-
return np.clip(blended, 0, 255).astype(np.uint8)
|
| 287 |
|
| 288 |
|
| 289 |
-
def make_timelapse_gif(
|
| 290 |
-
"""Create a smooth cross-faded
|
| 291 |
labels = [
|
| 292 |
-
"
|
| 293 |
-
"
|
| 294 |
-
"
|
| 295 |
-
"
|
| 296 |
-
"
|
|
|
|
|
|
|
| 297 |
]
|
| 298 |
-
h, w =
|
| 299 |
-
bar_h =
|
| 300 |
|
| 301 |
-
def _annotate(arr: np.ndarray, text: str) -> Image.Image:
|
| 302 |
-
canvas = Image.new("RGB", (w, h + bar_h), (
|
| 303 |
canvas.paste(Image.fromarray(arr), (0, bar_h))
|
| 304 |
draw = ImageDraw.Draw(canvas)
|
| 305 |
-
draw.text((
|
|
|
|
|
|
|
|
|
|
| 306 |
return canvas
|
| 307 |
|
| 308 |
frames: List[Image.Image] = []
|
| 309 |
durations: List[int] = []
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
if i < len(stages) - 1:
|
| 317 |
-
nxt = stages[i + 1]
|
| 318 |
-
for alpha in (0.25, 0.50, 0.75):
|
| 319 |
blend = cv2.addWeighted(img, 1.0 - alpha, nxt, alpha, 0)
|
| 320 |
-
frames.append(_annotate(blend, labels[i + 1]))
|
| 321 |
durations.append(95)
|
| 322 |
|
| 323 |
tmp = tempfile.NamedTemporaryFile(suffix=".gif", delete=False)
|
| 324 |
tmp.close()
|
| 325 |
-
frames[0].save(
|
| 326 |
-
tmp.name,
|
| 327 |
-
save_all=True,
|
| 328 |
-
append_images=frames[1:],
|
| 329 |
-
duration=durations,
|
| 330 |
-
loop=0,
|
| 331 |
-
optimize=True,
|
| 332 |
-
)
|
| 333 |
return tmp.name
|
| 334 |
|
| 335 |
|
| 336 |
-
def
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
img_lab = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2LAB).astype(np.float32)
|
| 343 |
-
|
| 344 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
-
mask = cv2.GaussianBlur((nearest == color_idx).astype(np.float32), (5, 5), 0)[..., None]
|
| 347 |
bg = cv2.cvtColor(cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB).astype(np.float32) * 0.25 + 188.0
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
|
| 360 |
|
| 361 |
def render_palette_card(palette: List[PaletteColor]) -> np.ndarray:
|
| 362 |
card_w, row_h = 720, 50
|
| 363 |
-
im = Image.new("RGB", (card_w, 42 + len(palette) * row_h), (
|
| 364 |
draw = ImageDraw.Draw(im)
|
| 365 |
-
draw.text((16, 12), "
|
| 366 |
for i, c in enumerate(palette):
|
| 367 |
y0 = 38 + i * row_h
|
| 368 |
draw.rectangle([16, y0 + 5, 80, y0 + row_h - 5], fill=c.rgb, outline=(60, 60, 60), width=1)
|
| 369 |
recipe_str = " + ".join(f"{pct}% {name}" for name, pct in c.mixing_recipe)
|
| 370 |
draw.text((94, y0 + 6), f"#{c.index + 1} {c.hex} ({c.proportion * 100:.1f}%)", fill=(25, 25, 25))
|
| 371 |
-
draw.text((94, y0 + 25), f"Mix: {recipe_str}", fill=(
|
| 372 |
return np.array(im)
|
| 373 |
|
| 374 |
|
|
@@ -403,38 +522,40 @@ def evaluate_amateur_painting(ref_img: np.ndarray, user_img: np.ndarray) -> Tupl
|
|
| 403 |
|
| 404 |
tips = []
|
| 405 |
if val_diff > 10:
|
| 406 |
-
tips.append("- **سایهها کمی زیادی روشناند:** در نواحی قرمز نقشه، سایهها را با
|
| 407 |
elif val_diff < -10:
|
| 408 |
-
tips.append("- **نقاشی کمی تیره شده:** در بخشهای روشن کمی
|
| 409 |
else:
|
| 410 |
tips.append("- **تعادل نور و سایه عالی است!**")
|
| 411 |
if color_score < 65:
|
| 412 |
-
tips.append("- **دقت رنگ:**
|
| 413 |
if struct_score < 55:
|
| 414 |
-
tips.append("- **تناسبات:** با شبکه 4×4 ا
|
| 415 |
|
| 416 |
report = (
|
| 417 |
f"### 🏆 امتیاز کلی نقاشی تو: **{overall:.1f} / 100**\n"
|
| 418 |
f"- دقت رنگها: `{color_score:.1f}` | تعادل نور و سایه: `{value_score:.1f}` | تناسبات: `{struct_score:.1f}`\n\n"
|
| 419 |
-
f"#### 💡
|
| 420 |
)
|
| 421 |
return overlay, report
|
| 422 |
|
| 423 |
|
| 424 |
# ============================================================
|
| 425 |
-
# 3.
|
| 426 |
# ============================================================
|
| 427 |
HERE = Path(__file__).resolve().parent
|
| 428 |
DEFAULT_HF_REPO = "tarfandoon/paintpath-net"
|
| 429 |
ON_SPACES = bool(os.environ.get("SPACE_ID"))
|
| 430 |
MODEL = None
|
| 431 |
|
| 432 |
-
|
| 433 |
-
1: "###
|
| 434 |
-
2: "###
|
| 435 |
-
3: "###
|
| 436 |
-
4: "###
|
| 437 |
-
5: "###
|
|
|
|
|
|
|
| 438 |
}
|
| 439 |
|
| 440 |
|
|
@@ -469,7 +590,7 @@ def _gpu_decorator(fn):
|
|
| 469 |
@torch.no_grad()
|
| 470 |
def run_paintpath_studio(input_img: np.ndarray, num_colors: int, show_grid: bool):
|
| 471 |
if input_img is None or MODEL is None:
|
| 472 |
-
return None, None, None, "لطفاً ابتدا یک
|
| 473 |
|
| 474 |
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 475 |
MODEL.to(dev)
|
|
@@ -485,35 +606,46 @@ def run_paintpath_studio(input_img: np.ndarray, num_colors: int, show_grid: bool
|
|
| 485 |
gpu_name = torch.cuda.get_device_name(0) if dev.type == "cuda" else ""
|
| 486 |
use_amp = (dev.type == "cuda") and ("1650" not in gpu_name and "1660" not in gpu_name)
|
| 487 |
|
| 488 |
-
|
| 489 |
with torch.amp.autocast("cuda", enabled=use_amp, dtype=torch.float16):
|
| 490 |
focal_t = MODEL.extract_focal_map(inp)
|
| 491 |
for s_idx in range(4):
|
| 492 |
st = torch.tensor([s_idx], dtype=torch.long, device=dev)
|
| 493 |
pred = MODEL(inp, st)
|
| 494 |
arr = (pred[0].float().clamp(0, 1).permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8)
|
| 495 |
-
|
| 496 |
|
| 497 |
focal_01 = focal_t[0, 0].float().cpu().numpy()
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
blank = np.full_like(resized, 248)
|
| 505 |
-
|
| 506 |
-
1:
|
| 507 |
-
2:
|
| 508 |
-
3:
|
| 509 |
-
4:
|
| 510 |
-
5:
|
|
|
|
|
|
|
| 511 |
}
|
| 512 |
-
step_imgs = {1: s1, 2: s2, 3: s3, 4: s4, 5: resized}
|
| 513 |
|
| 514 |
palette = extract_physical_palette(resized, k=int(num_colors))
|
| 515 |
pal_card = render_palette_card(palette)
|
| 516 |
-
loc_img,
|
| 517 |
color_choices = [f"رنگ #{c.index + 1} ({c.hex}) — {c.proportion * 100:.1f}%" for c in palette]
|
| 518 |
|
| 519 |
attention_img = make_attention_overlay(resized, focal_01)
|
|
@@ -522,112 +654,133 @@ def run_paintpath_studio(input_img: np.ndarray, num_colors: int, show_grid: bool
|
|
| 522 |
state = {
|
| 523 |
"resized": resized,
|
| 524 |
"step_imgs": step_imgs,
|
| 525 |
-
"
|
| 526 |
"palette": palette,
|
| 527 |
-
"step": 1,
|
| 528 |
}
|
| 529 |
|
| 530 |
return (
|
| 531 |
state,
|
| 532 |
-
|
|
|
|
| 533 |
step_imgs[1],
|
| 534 |
-
|
| 535 |
1,
|
|
|
|
| 536 |
pal_card,
|
| 537 |
loc_img,
|
| 538 |
-
|
| 539 |
gr.update(choices=color_choices, value=color_choices[0]),
|
| 540 |
attention_img,
|
| 541 |
value_study,
|
| 542 |
)
|
| 543 |
|
| 544 |
|
| 545 |
-
def render_slide(step_num: int,
|
| 546 |
if not state:
|
| 547 |
return None, "ابتدا یک نقاشی آپلود کن.", 1
|
| 548 |
-
s = max(1, min(
|
| 549 |
-
state["
|
| 550 |
-
img
|
| 551 |
-
return img, STEP_GUIDES[s], s
|
| 552 |
|
| 553 |
|
| 554 |
-
def prev_slide(step_num: int,
|
| 555 |
-
return render_slide(max(1, int(step_num) - 1),
|
| 556 |
|
| 557 |
|
| 558 |
-
def next_slide(step_num: int,
|
| 559 |
-
return render_slide(min(
|
| 560 |
|
| 561 |
|
| 562 |
-
def
|
| 563 |
if not state or not color_label:
|
| 564 |
-
return None, "
|
| 565 |
try:
|
| 566 |
idx = int(color_label.split("#")[1].split(" ")[0]) - 1
|
| 567 |
except Exception:
|
| 568 |
idx = 0
|
| 569 |
idx = max(0, min(idx, len(state["palette"]) - 1))
|
| 570 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 571 |
|
| 572 |
|
| 573 |
# ============================================================
|
| 574 |
-
# 4.
|
| 575 |
# ============================================================
|
| 576 |
CUSTOM_CSS = """
|
| 577 |
-
.
|
| 578 |
-
background: linear-gradient(135deg, #
|
| 579 |
-
border:
|
| 580 |
-
border-radius:
|
| 581 |
-
padding: 24px 28px;
|
| 582 |
-
margin-bottom:
|
| 583 |
-
|
| 584 |
-
|
| 585 |
}
|
| 586 |
-
.
|
| 587 |
-
margin: 0 0 8px 0;
|
| 588 |
-
font-size:
|
| 589 |
-
font-weight:
|
| 590 |
-
|
| 591 |
-
color: #ffffff;
|
| 592 |
}
|
| 593 |
-
.
|
| 594 |
-
margin: 0 auto
|
| 595 |
-
max-width:
|
| 596 |
-
font-size: 1.
|
| 597 |
-
|
|
|
|
| 598 |
}
|
| 599 |
-
.
|
| 600 |
-
display: flex;
|
| 601 |
-
justify-content: center;
|
| 602 |
-
flex-wrap: wrap;
|
| 603 |
-
gap: 10px;
|
| 604 |
}
|
| 605 |
-
.
|
| 606 |
-
display: inline-flex;
|
| 607 |
-
align-items: center;
|
| 608 |
-
gap: 6px;
|
| 609 |
-
padding:
|
| 610 |
-
border-radius: 999px;
|
| 611 |
-
background:
|
| 612 |
-
border: 1px solid rgba(255, 255, 255, 0.18);
|
| 613 |
color: #ffffff !important;
|
| 614 |
text-decoration: none !important;
|
| 615 |
-
font-size: 0.88rem;
|
| 616 |
-
font-weight:
|
| 617 |
-
|
| 618 |
}
|
| 619 |
-
.
|
| 620 |
-
background:
|
| 621 |
-
|
| 622 |
-
transform: translateY(-1px);
|
| 623 |
}
|
| 624 |
-
.
|
| 625 |
-
text-align: center;
|
| 626 |
-
margin-top:
|
| 627 |
-
padding:
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 631 |
}
|
| 632 |
"""
|
| 633 |
|
|
@@ -638,10 +791,10 @@ def build_ui():
|
|
| 638 |
|
| 639 |
gr.HTML(
|
| 640 |
"""
|
| 641 |
-
<div class="
|
| 642 |
-
<h1>🎨 PaintPath Studio</h1>
|
| 643 |
-
<p>همیشه انسان کار را برای هوش مصنوعی ساده میکند؛ این بار هوش مصنوعی
|
| 644 |
-
<div class="
|
| 645 |
<a href="https://jahaniwww.com" target="_blank">👤 Ali Jahani — jahaniwww.com</a>
|
| 646 |
<a href="https://t.me/tarfandoonchannel" target="_blank">✈️ Telegram: @tarfandoonchannel</a>
|
| 647 |
<a href="https://huggingface.co/tarfandoon/paintpath-net" target="_blank">🤗 Model: tarfandoon/paintpath-net</a>
|
|
@@ -650,58 +803,64 @@ def build_ui():
|
|
| 650 |
"""
|
| 651 |
)
|
| 652 |
|
| 653 |
-
# Clean
|
| 654 |
with gr.Row(equal_height=True):
|
| 655 |
with gr.Column(scale=2):
|
| 656 |
-
in_img = gr.Image(type="numpy", label="نقاشی مورد نظرت را اینجا
|
| 657 |
with gr.Column(scale=1):
|
| 658 |
-
gr.Markdown("###
|
| 659 |
-
run_btn = gr.Button("✨ ساخت ا
|
| 660 |
with gr.Accordion("⚙️ تنظیمات اختیاری", open=False):
|
| 661 |
-
num_colors = gr.Slider(6, 12, value=8, step=1, label="تعداد رنگهای پالت")
|
| 662 |
show_grid = gr.Checkbox(value=True, label="نمایش شبکه تناسبات (4×4) روی اسکچ")
|
| 663 |
|
| 664 |
with gr.Tabs():
|
| 665 |
-
# TAB 1:
|
| 666 |
-
with gr.Tab("🎬 ۱.
|
| 667 |
with gr.Row():
|
| 668 |
with gr.Column(scale=1):
|
| 669 |
-
gr.Markdown("###
|
| 670 |
-
|
|
|
|
|
|
|
|
|
|
| 671 |
with gr.Column(scale=1):
|
| 672 |
-
gr.Markdown("### 🖼️ اسلاید تعاملی
|
| 673 |
-
slide_img = gr.Image(label="
|
| 674 |
with gr.Row():
|
| 675 |
prev_btn = gr.Button("⬅️ مرحله قبل")
|
| 676 |
next_btn = gr.Button("مرحله بعد ➡️", variant="primary")
|
| 677 |
with gr.Row():
|
| 678 |
-
step_slider = gr.Slider(1,
|
| 679 |
-
|
| 680 |
-
slide_guide = gr.Markdown(
|
| 681 |
|
| 682 |
-
# TAB 2:
|
| 683 |
-
with gr.Tab("
|
| 684 |
-
gr.Markdown(
|
| 685 |
-
"### 🔥 نگاهِ مغز هوش مصنوعی به نقاشی\n"
|
| 686 |
-
"مدل `PaintPathNet` نشان میدهد **چشم بیننده اول به کجا خیره میشود** (نقاط گرم و درخشان = بیشترین کشش بصری) و در کنارش **مطالعه ۳ سطحی نور و سایه** را میدهد."
|
| 687 |
-
)
|
| 688 |
with gr.Row():
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
# TAB 3: Physical Palette & Color-by-Color Canvas Locator
|
| 693 |
-
with gr.Tab("🎨 ۳. پالت ترکیب رنگ و محل هر رنگ"):
|
| 694 |
with gr.Row():
|
| 695 |
with gr.Column(scale=1):
|
| 696 |
-
|
|
|
|
| 697 |
with gr.Column(scale=1):
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 701 |
|
| 702 |
# TAB 4: Check My Hand-Painted Canvas
|
| 703 |
with gr.Tab("🏆 ۴. ارزیابی نقاشیِ دستِ تو"):
|
| 704 |
-
gr.Markdown("از نقاشیای که خودت با دست روی بوم یا کاغذ کشیدی عکس بگیر و اینجا
|
| 705 |
with gr.Row():
|
| 706 |
user_canvas_in = gr.Image(type="numpy", label="📸 عکس نقاشیِ دستِ خودت")
|
| 707 |
feedback_img_out = gr.Image(label="🔍 نقشه اصلاح (قرمز = نیاز به اصلاح، آبی = عالی)")
|
|
@@ -710,10 +869,10 @@ def build_ui():
|
|
| 710 |
|
| 711 |
gr.HTML(
|
| 712 |
"""
|
| 713 |
-
<div class="
|
| 714 |
ساختهشده با ❤️ توسط <b>Ali Jahani</b> |
|
| 715 |
-
🌐 <a href="https://jahaniwww.com" target="_blank">jahaniwww.com</a> |
|
| 716 |
-
✈️ <a href="https://t.me/tarfandoonchannel" target="_blank">
|
| 717 |
</div>
|
| 718 |
"""
|
| 719 |
)
|
|
@@ -724,13 +883,15 @@ def build_ui():
|
|
| 724 |
inputs=[in_img, num_colors, show_grid],
|
| 725 |
outputs=[
|
| 726 |
studio_state,
|
|
|
|
| 727 |
timelapse_out,
|
| 728 |
slide_img,
|
| 729 |
slide_guide,
|
| 730 |
step_slider,
|
|
|
|
| 731 |
pal_out,
|
| 732 |
color_loc_img,
|
| 733 |
-
|
| 734 |
color_dropdown,
|
| 735 |
attn_out,
|
| 736 |
val_out,
|
|
@@ -739,28 +900,33 @@ def build_ui():
|
|
| 739 |
|
| 740 |
step_slider.change(
|
| 741 |
fn=render_slide,
|
| 742 |
-
inputs=[step_slider,
|
| 743 |
outputs=[slide_img, slide_guide, step_slider],
|
| 744 |
)
|
| 745 |
-
|
| 746 |
fn=render_slide,
|
| 747 |
-
inputs=[step_slider,
|
| 748 |
outputs=[slide_img, slide_guide, step_slider],
|
| 749 |
)
|
| 750 |
prev_btn.click(
|
| 751 |
fn=prev_slide,
|
| 752 |
-
inputs=[step_slider,
|
| 753 |
outputs=[slide_img, slide_guide, step_slider],
|
| 754 |
)
|
| 755 |
next_btn.click(
|
| 756 |
fn=next_slide,
|
| 757 |
-
inputs=[step_slider,
|
| 758 |
outputs=[slide_img, slide_guide, step_slider],
|
| 759 |
)
|
| 760 |
color_dropdown.change(
|
| 761 |
-
fn=
|
| 762 |
inputs=[color_dropdown, studio_state],
|
| 763 |
-
outputs=[color_loc_img,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 764 |
)
|
| 765 |
check_btn.click(
|
| 766 |
fn=evaluate_amateur_painting,
|
|
|
|
| 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
|
|
|
|
| 147 |
|
| 148 |
|
| 149 |
# ============================================================
|
| 150 |
+
# 2. Physical Pigment Mixing, 7-Stage Builder & Animations
|
| 151 |
# ============================================================
|
| 152 |
ARTIST_TUBES: Dict[str, Tuple[int, int, int]] = {
|
| 153 |
"Titanium White": (245, 245, 242),
|
|
|
|
| 160 |
"Viridian Green": (34, 118, 88),
|
| 161 |
}
|
| 162 |
|
| 163 |
+
TUBE_PERSIAN = {
|
| 164 |
+
"Titanium White": "سفید تیتانیوم",
|
| 165 |
+
"Ivory Black": "مشکی عاجی",
|
| 166 |
+
"Ultramarine Blue": "آبی اولترامارین",
|
| 167 |
+
"Cadmium Red": "قرمز کادمیوم",
|
| 168 |
+
"Cadmium Yellow": "زرد کادمیوم",
|
| 169 |
+
"Yellow Ochre": "زرد اخرایی",
|
| 170 |
+
"Burnt Umber": "قهوهای سوخته (آمبر)",
|
| 171 |
+
"Viridian Green": "سبز ویریدین",
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
|
| 175 |
def _srgb_to_linear(rgb01: np.ndarray) -> np.ndarray:
|
| 176 |
return np.where(rgb01 <= 0.04045, rgb01 / 12.92, ((rgb01 + 0.055) / 1.055) ** 2.4)
|
|
|
|
| 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_like(sketch_rgb, 252)
|
| 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 |
+
Animated line-by-line Pencil Sketching GIF!
|
| 300 |
+
Extracts contours from PaintPathNet's Stage 1 sketch, orders them from
|
| 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 |
+
inv = (gray < 200).astype(np.uint8) * 255
|
| 306 |
+
contours, _ = cv2.findContours(inv, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
|
| 307 |
+
contours = sorted(contours, key=lambda c: cv2.arcLength(c, False), reverse=True)
|
| 308 |
+
|
| 309 |
+
base = np.full((h, w, 3), 252, dtype=np.uint8)
|
| 310 |
+
if show_grid:
|
| 311 |
+
base = add_proportion_grid(base, 4)
|
| 312 |
+
|
| 313 |
+
n_frames = 18
|
| 314 |
+
frames: List[Image.Image] = []
|
| 315 |
+
durations: List[int] = []
|
| 316 |
+
bar_h = 30
|
| 317 |
+
|
| 318 |
+
def _frame_with_bar(arr: np.ndarray, pct: int) -> Image.Image:
|
| 319 |
+
out = Image.new("RGB", (w, h + bar_h), (245, 241, 234))
|
| 320 |
+
out.paste(Image.fromarray(arr), (0, bar_h))
|
| 321 |
+
d = ImageDraw.Draw(out)
|
| 322 |
+
d.text((10, 7), f"Animated Sketch Guide — {pct}%", fill=(35, 35, 45))
|
| 323 |
+
# Progress bar
|
| 324 |
+
bar_w = int((w - 20) * pct / 100)
|
| 325 |
+
d.rectangle([10, bar_h - 5, w - 10, bar_h - 2], fill=(220, 215, 205))
|
| 326 |
+
d.rectangle([10, bar_h - 5, 10 + bar_w, bar_h - 2], fill=(217, 119, 6))
|
| 327 |
+
return out
|
| 328 |
+
|
| 329 |
+
canvas = base.copy()
|
| 330 |
+
total_c = max(len(contours), 1)
|
| 331 |
+
for f in range(1, n_frames):
|
| 332 |
+
# Ease-in so major shapes draw first, then details fill in smoothly
|
| 333 |
+
frac = (f / (n_frames - 1)) ** 1.35
|
| 334 |
+
k = max(1, int(total_c * frac))
|
| 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 |
+
# Final crisp PaintPathNet sketch frame held for 2s
|
| 341 |
+
final_sk = add_proportion_grid(sketch_rgb, 4) if show_grid else sketch_rgb
|
| 342 |
+
frames.append(_frame_with_bar(final_sk, 100))
|
| 343 |
+
durations.append(2200)
|
| 344 |
|
| 345 |
+
tmp = tempfile.NamedTemporaryFile(suffix=".gif", delete=False)
|
| 346 |
+
tmp.close()
|
| 347 |
+
frames[0].save(tmp.name, save_all=True, append_images=frames[1:], duration=durations, loop=0, optimize=True)
|
| 348 |
+
return tmp.name
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
|
| 350 |
|
| 351 |
+
def make_timelapse_gif(stages_7: List[np.ndarray]) -> str:
|
| 352 |
+
"""Create a smooth cross-faded 7-stage painting timelapse GIF."""
|
| 353 |
labels = [
|
| 354 |
+
"1/7: Rough Shapes & Grid",
|
| 355 |
+
"2/7: Full Pencil Sketch",
|
| 356 |
+
"3/7: Monochrome Underpainting",
|
| 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, idx: int) -> Image.Image:
|
| 366 |
+
canvas = Image.new("RGB", (w, h + bar_h), (245, 241, 234))
|
| 367 |
canvas.paste(Image.fromarray(arr), (0, bar_h))
|
| 368 |
draw = ImageDraw.Draw(canvas)
|
| 369 |
+
draw.text((10, 7), text, fill=(30, 30, 40))
|
| 370 |
+
prog = int((w - 20) * (idx + 1) / len(stages_7))
|
| 371 |
+
draw.rectangle([10, bar_h - 5, w - 10, bar_h - 2], fill=(220, 215, 205))
|
| 372 |
+
draw.rectangle([10, bar_h - 5, 10 + prog, bar_h - 2], fill=(79, 70, 229))
|
| 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(1150 if i < len(stages_7) - 1 else 2300)
|
| 380 |
+
if i < len(stages_7) - 1:
|
| 381 |
+
nxt = stages_7[i + 1]
|
| 382 |
+
for alpha in (0.33, 0.66):
|
|
|
|
|
|
|
|
|
|
| 383 |
blend = cv2.addWeighted(img, 1.0 - alpha, nxt, alpha, 0)
|
| 384 |
+
frames.append(_annotate(blend, labels[i + 1], i + 1))
|
| 385 |
durations.append(95)
|
| 386 |
|
| 387 |
tmp = tempfile.NamedTemporaryFile(suffix=".gif", delete=False)
|
| 388 |
tmp.close()
|
| 389 |
+
frames[0].save(tmp.name, save_all=True, append_images=frames[1:], duration=durations, loop=0, optimize=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
return tmp.name
|
| 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)))
|
| 398 |
+
bin_mask = (diff >= thr).astype(np.uint8) * 255
|
| 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 + 160.0
|
| 403 |
+
blended = 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
|
| 409 |
|
| 410 |
+
|
| 411 |
+
def make_value_study_3tone(img_rgb: np.ndarray) -> np.ndarray:
|
| 412 |
+
gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
|
| 413 |
+
gray = cv2.bilateralFilter(gray, 9, 55, 55)
|
| 414 |
+
t1, t2 = np.percentile(gray, [33, 72])
|
| 415 |
+
out = np.full_like(gray, 138)
|
| 416 |
+
out[gray <= t1] = 28
|
| 417 |
+
out[gray >= t2] = 242
|
| 418 |
+
return cv2.cvtColor(out, cv2.COLOR_GRAY2RGB)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def make_attention_overlay(img_rgb: np.ndarray, focal_01: np.ndarray) -> np.ndarray:
|
| 422 |
+
heat_u8 = np.clip(focal_01 * 255.0, 0, 255).astype(np.uint8)
|
| 423 |
+
heat_u8 = cv2.GaussianBlur(heat_u8, (15, 15), 0)
|
| 424 |
+
heat_bgr = cv2.applyColorMap(heat_u8, cv2.COLORMAP_INFERNO)
|
| 425 |
+
heat_rgb = cv2.cvtColor(heat_bgr, cv2.COLOR_BGR2RGB)
|
| 426 |
+
return cv2.addWeighted(img_rgb, 0.50, heat_rgb, 0.50, 0)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def highlight_target_rgb_on_canvas(img_rgb: np.ndarray, target_rgb: Tuple[int, int, int], tolerance: float = 26.0) -> Tuple[np.ndarray, str]:
|
| 430 |
+
"""Highlight ALL regions on the canvas matching `target_rgb` + render physical mixing recipe HTML."""
|
| 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)
|
| 434 |
+
|
| 435 |
+
mask = np.clip(1.0 - (dist - tolerance * 0.5) / max(tolerance, 1.0), 0.0, 1.0)
|
| 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.25 + 188.0
|
| 440 |
+
out = 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)
|
| 443 |
+
|
| 444 |
+
r, g, b = target_rgb
|
| 445 |
+
hex_code = f"#{r:02X}{g:02X}{b:02X}"
|
| 446 |
+
recipe = solve_tube_recipe(target_rgb)
|
| 447 |
+
|
| 448 |
+
bars_html = ""
|
| 449 |
+
for name, pct in recipe:
|
| 450 |
+
tr, tg, tb = ARTIST_TUBES[name]
|
| 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:600;">
|
| 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.15);"></div>
|
| 460 |
+
</div>
|
| 461 |
+
</div>
|
| 462 |
+
"""
|
| 463 |
+
|
| 464 |
+
card_html = f"""
|
| 465 |
+
<div style="background:#fffdf9; border:1px solid #e5dfd5; border-radius:14px; padding:16px; direction:rtl; color:#1f2937 !important;">
|
| 466 |
+
<div style="display:flex; align-items:center; gap:14px; margin-bottom:12px;">
|
| 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}) — نواحی دارای کادر قرمز در تصویر، دقیقاً محل استفاده این رنگ هستند!</div>
|
| 471 |
+
</div>
|
| 472 |
+
</div>
|
| 473 |
+
<div style="font-size:14px; font-weight:700; color:#111827 !important; margin-bottom:6px;">🧪 دستور ترکیب واقعی رنگهای تیوپی (فیزیک Kubelka-Munk):</div>
|
| 474 |
+
{bars_html}
|
| 475 |
+
</div>
|
| 476 |
+
"""
|
| 477 |
+
return out, card_html
|
| 478 |
|
| 479 |
|
| 480 |
def render_palette_card(palette: List[PaletteColor]) -> np.ndarray:
|
| 481 |
card_w, row_h = 720, 50
|
| 482 |
+
im = Image.new("RGB", (card_w, 42 + len(palette) * row_h), (252, 250, 246))
|
| 483 |
draw = ImageDraw.Draw(im)
|
| 484 |
+
draw.text((16, 12), "Master Palette — Physical Paint-Tube Mixing Recipes", fill=(30, 30, 35))
|
| 485 |
for i, c in enumerate(palette):
|
| 486 |
y0 = 38 + i * row_h
|
| 487 |
draw.rectangle([16, y0 + 5, 80, y0 + row_h - 5], fill=c.rgb, outline=(60, 60, 60), width=1)
|
| 488 |
recipe_str = " + ".join(f"{pct}% {name}" for name, pct in c.mixing_recipe)
|
| 489 |
draw.text((94, y0 + 6), f"#{c.index + 1} {c.hex} ({c.proportion * 100:.1f}%)", fill=(25, 25, 25))
|
| 490 |
+
draw.text((94, y0 + 25), f"Mix: {recipe_str}", fill=(75, 75, 80))
|
| 491 |
return np.array(im)
|
| 492 |
|
| 493 |
|
|
|
|
| 522 |
|
| 523 |
tips = []
|
| 524 |
if val_diff > 10:
|
| 525 |
+
tips.append("- **سایهها کمی زیادی روشناند:** در نواحی قرمز نقشه، سایهها را با کمی قهوهای سوخته (Burnt Umber) عمیقتر کن.")
|
| 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("- **تناسبات:** با انیمیشن اسکچ و شبکه 4×4 گام ۱ جای اصلی اشیا را چک کن.")
|
| 534 |
|
| 535 |
report = (
|
| 536 |
f"### 🏆 امتیاز کلی نقاشی تو: **{overall:.1f} / 100**\n"
|
| 537 |
f"- دقت رنگها: `{color_score:.1f}` | تعادل نور و سایه: `{value_score:.1f}` | تناسبات: `{struct_score:.1f}`\n\n"
|
| 538 |
+
f"#### 💡 توصیههای مربی (قرمز = نیاز به اصلاح، آبی = عالی):\n" + "\n".join(tips)
|
| 539 |
)
|
| 540 |
return overlay, report
|
| 541 |
|
| 542 |
|
| 543 |
# ============================================================
|
| 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 |
+
STEP_GUIDES_7 = {
|
| 552 |
+
1: "### 📐 گام ۱ از ۷ — خطوط اصلی و تناسبات *(مداد HB، خیلی کمرنگ)*\nبا کمک شبکه **4×4** فقط کادر و شکلهای بزرگ را روی بوم بگذار. اصلاً سراغ جزئیات نرو؛ فقط جای درست اشیا مهم است!",
|
| 553 |
+
2: "### ✏️ گام ۲ از ۷ — اسکچ کامل مدادی *(مداد 2B)*\nانیمیشن اسکچ سمت چپ را ببین و خطوط کامل اشیا را روی طرح مرحله ۱ دقیق کن. الان نقشه بوم تو کامل شد.",
|
| 554 |
+
3: "### 🤎 گام ۳ از ۷ — زیررنگگذاری تکرنگ *(قلم تخت پهن #14، رنگ رقیق قهوهای سوخته + سفید)*\nیک تکنیک کلاسیک استادان نقاشی! قبل از رنگ اصلی، فقط تیرگی و روشنی کلی را با یک رنگ قهوهای رقیق روی بوم پیاده کن تا حجم سریع دربیاید.",
|
| 555 |
+
4: "### 🖌️ گام ۴ از ۷ — رنگگذاری پایه و لکههای بزرگ *(قلم تخت پهن #12)*\nتیک **«نشان بده کجا را رنگ کنم»** را بزن و هر ناحیه بزرگ را با رنگ پایهاش از تب پالت پر کن. بگذار رنگها ساده و تخت بمانند.",
|
| 556 |
+
5: "### 🌗 گام ۵ از ۷ — سایهها و عمقدهی *(قلم متوسط #8)*\nنواحی دارای کادر نارنجی دقیقاً جاهایی هستند که باید **سایه و حجم** اضافه کنی تا اشیا از بوم بیرون بزنند.",
|
| 557 |
+
6: "### ✨ گام ۶ از ۷ — جزئیات میانی و بافت قلممو *(قلم گرد #3)*\nلبهها را تمیز کن، بافتهای اصلی را بکش و مرز بین سایه و نور را نرمتر کن.",
|
| 558 |
+
7: "### 🌟 گام ۷ از ۷ — هایلایتها و ضربههای نهایی *(قلم ریز #0-#1)*\nبا رنگ غلیظ و روشن، فقط همان چند نقطه نور و کنتراست آخر را بزن تا نقاشی زنده و درخشان شود!",
|
| 559 |
}
|
| 560 |
|
| 561 |
|
|
|
|
| 590 |
@torch.no_grad()
|
| 591 |
def run_paintpath_studio(input_img: np.ndarray, num_colors: int, show_grid: bool):
|
| 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)
|
|
|
|
| 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 |
+
stages_raw = []
|
| 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(4):
|
| 613 |
st = torch.tensor([s_idx], dtype=torch.long, device=dev)
|
| 614 |
pred = MODEL(inp, st)
|
| 615 |
arr = (pred[0].float().clamp(0, 1).permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8)
|
| 616 |
+
stages_raw.append(arr)
|
| 617 |
|
| 618 |
focal_01 = focal_t[0, 0].float().cpu().numpy()
|
| 619 |
+
m_sketch, m_block, m_shadow, m_detail = stages_raw
|
| 620 |
+
|
| 621 |
+
# Build 7 complete, beginner-friendly painting stages!
|
| 622 |
+
st1 = make_rough_shapes_sketch(m_sketch, show_grid=show_grid)
|
| 623 |
+
st2 = add_proportion_grid(m_sketch, 4) if show_grid else m_sketch
|
| 624 |
+
st3 = make_sepia_underpainting(m_block)
|
| 625 |
+
st4 = m_block
|
| 626 |
+
st5 = m_shadow
|
| 627 |
+
st6 = m_detail
|
| 628 |
+
st7 = resized
|
| 629 |
+
|
| 630 |
+
all_7 = [st1, st2, st3, st4, st5, st6, st7]
|
| 631 |
+
sketch_gif = make_sketch_animation_gif(m_sketch, show_grid=show_grid)
|
| 632 |
+
timelapse_gif = make_timelapse_gif(all_7)
|
| 633 |
+
|
| 634 |
+
step_imgs = {i + 1: all_7[i] for i in range(7)}
|
| 635 |
blank = np.full_like(resized, 248)
|
| 636 |
+
paint_zones = {
|
| 637 |
+
1: st1,
|
| 638 |
+
2: st2,
|
| 639 |
+
3: make_clear_paint_zones(blank, st3),
|
| 640 |
+
4: make_clear_paint_zones(st3, st4),
|
| 641 |
+
5: make_clear_paint_zones(st4, st5),
|
| 642 |
+
6: make_clear_paint_zones(st5, st6),
|
| 643 |
+
7: make_clear_paint_zones(st6, st7),
|
| 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)
|
| 649 |
color_choices = [f"رنگ #{c.index + 1} ({c.hex}) — {c.proportion * 100:.1f}%" for c in palette]
|
| 650 |
|
| 651 |
attention_img = make_attention_overlay(resized, focal_01)
|
|
|
|
| 654 |
state = {
|
| 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 |
+
STEP_GUIDES_7[1],
|
| 667 |
1,
|
| 668 |
+
resized,
|
| 669 |
pal_card,
|
| 670 |
loc_img,
|
| 671 |
+
loc_html,
|
| 672 |
gr.update(choices=color_choices, value=color_choices[0]),
|
| 673 |
attention_img,
|
| 674 |
value_study,
|
| 675 |
)
|
| 676 |
|
| 677 |
|
| 678 |
+
def render_slide(step_num: int, show_zones: bool, state: Optional[dict]):
|
| 679 |
if not state:
|
| 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, STEP_GUIDES_7[s], s
|
|
|
|
| 684 |
|
| 685 |
|
| 686 |
+
def prev_slide(step_num: int, show_zones: bool, state: Optional[dict]):
|
| 687 |
+
return render_slide(max(1, int(step_num) - 1), show_zones, state)
|
| 688 |
|
| 689 |
|
| 690 |
+
def next_slide(step_num: int, show_zones: bool, state: Optional[dict]):
|
| 691 |
+
return render_slide(min(7, int(step_num) + 1), show_zones, state)
|
| 692 |
|
| 693 |
|
| 694 |
+
def on_color_dropdown(color_label: str, state: Optional[dict]):
|
| 695 |
if not state or not color_label:
|
| 696 |
+
return None, ""
|
| 697 |
try:
|
| 698 |
idx = int(color_label.split("#")[1].split(" ")[0]) - 1
|
| 699 |
except Exception:
|
| 700 |
idx = 0
|
| 701 |
idx = max(0, min(idx, len(state["palette"]) - 1))
|
| 702 |
+
return highlight_target_rgb_on_canvas(state["resized"], state["palette"][idx].rgb)
|
| 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 Studio UI (Light & Dark Mode Safe!)
|
| 722 |
# ============================================================
|
| 723 |
CUSTOM_CSS = """
|
| 724 |
+
.studio-hero {
|
| 725 |
+
background: linear-gradient(135deg, #fff8ec 0%, #fef3e2 50%, #eef2ff 100%) !important;
|
| 726 |
+
border: 2px solid #e7d5bc !important;
|
| 727 |
+
border-radius: 20px !important;
|
| 728 |
+
padding: 24px 28px !important;
|
| 729 |
+
margin-bottom: 18px !important;
|
| 730 |
+
text-align: center !important;
|
| 731 |
+
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06) !important;
|
| 732 |
}
|
| 733 |
+
.studio-hero h1 {
|
| 734 |
+
margin: 0 0 8px 0 !important;
|
| 735 |
+
font-size: 2.05rem !important;
|
| 736 |
+
font-weight: 900 !important;
|
| 737 |
+
color: #111827 !important;
|
|
|
|
| 738 |
}
|
| 739 |
+
.studio-hero p {
|
| 740 |
+
margin: 0 auto 16px auto !important;
|
| 741 |
+
max-width: 760px !important;
|
| 742 |
+
font-size: 1.04rem !important;
|
| 743 |
+
font-weight: 500 !important;
|
| 744 |
+
color: #374151 !important;
|
| 745 |
}
|
| 746 |
+
.brand-links {
|
| 747 |
+
display: flex !important;
|
| 748 |
+
justify-content: center !important;
|
| 749 |
+
flex-wrap: wrap !important;
|
| 750 |
+
gap: 10px !important;
|
| 751 |
}
|
| 752 |
+
.brand-links a {
|
| 753 |
+
display: inline-flex !important;
|
| 754 |
+
align-items: center !important;
|
| 755 |
+
gap: 6px !important;
|
| 756 |
+
padding: 7px 16px !important;
|
| 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;
|
| 767 |
+
color: #ffffff !important;
|
|
|
|
| 768 |
}
|
| 769 |
+
.studio-footer {
|
| 770 |
+
text-align: center !important;
|
| 771 |
+
margin-top: 24px !important;
|
| 772 |
+
padding: 16px !important;
|
| 773 |
+
background: #fff8ec !important;
|
| 774 |
+
border: 1px solid #e7d5bc !important;
|
| 775 |
+
border-radius: 14px !important;
|
| 776 |
+
color: #1f2937 !important;
|
| 777 |
+
font-size: 0.92rem !important;
|
| 778 |
+
font-weight: 600 !important;
|
| 779 |
+
}
|
| 780 |
+
.studio-footer a {
|
| 781 |
+
color: #b45309 !important;
|
| 782 |
+
text-decoration: none !important;
|
| 783 |
+
font-weight: 700 !important;
|
| 784 |
}
|
| 785 |
"""
|
| 786 |
|
|
|
|
| 791 |
|
| 792 |
gr.HTML(
|
| 793 |
"""
|
| 794 |
+
<div class="studio-hero">
|
| 795 |
+
<h1>🎨 PaintPath Studio — آموزش تعاملی نقاشی با هوش مصنوعی</h1>
|
| 796 |
+
<p>همیشه انسان کار را برای هوش مصنوعی ساده میکند؛ این بار هوش مصنوعی نقاشی را به <b>۷ مرحله ساده، انیمیشن اسکچ و دستور ترکیب رنگ واقعی</b> تبدیل میکند تا هر آماتوری نقاش بشود!</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: tarfandoon/paintpath-net</a>
|
|
|
|
| 803 |
"""
|
| 804 |
)
|
| 805 |
|
| 806 |
+
# Clean Upload Strip
|
| 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("### 🚀 شروع کن\nیک نقاشی آپلود کن و دکمه زیر را بزن تا **انیمیشن اسکچ، فیلم ۷ مرحلهای، قطرهچکان ساخت رنگ و نقشه توجه چشم** برایت ساخته شود.")
|
| 812 |
+
run_btn = gr.Button("✨ ساخت نقشه ۷ مرحلهای نقاشی", variant="primary", size="lg")
|
| 813 |
with gr.Accordion("⚙️ تنظیمات اختیاری", open=False):
|
| 814 |
+
num_colors = gr.Slider(6, 12, value=8, step=1, label="تعداد رنگهای پالت اصلی")
|
| 815 |
show_grid = gr.Checkbox(value=True, label="نمایش شبکه تناسبات (4×4) روی اسکچ")
|
| 816 |
|
| 817 |
with gr.Tabs():
|
| 818 |
+
# TAB 1: Animated Sketching + 7-Stage Timelapse & Interactive Slides
|
| 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(STEP_GUIDES_7[1])
|
| 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="👆 روی هر نقطه نقاشی کلیک کن (قطرهچکان هوشمند)", interactive=False)
|
| 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="یا از بین رنگهای اصلی پالت انتخاب کن:", interactive=True)
|
| 847 |
+
color_recipe_html = gr.HTML("<div style='padding:12px; color:#4b5563;'>پس از ساخت نقشه، روی نقاشی کلیک کن یا یک رنگ از منو انتخاب کن.</div>")
|
| 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 |
+
"### 🔥 کانون توجه چشم بیننده (استخراج مستقیم از مغز `PaintPathNet`)\n"
|
| 855 |
+
"نقاط زرد و قرمز نشان میدهند **چشم مخاطب اول به کجا خیره میشود** — در کنارش **مطالعه ۳ سطحی نور و سایه** کمک میکند حجم را مثل یک نقاش حرفهای دربیاوری."
|
| 856 |
+
)
|
| 857 |
+
with gr.Row():
|
| 858 |
+
attn_out = gr.Image(label="🔥 نقشه کانون توجه چشم (Eye Attention Heatmap)")
|
| 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="🔍 نقشه اصلاح (قرمز = نیاز به اصلاح، آبی = عالی)")
|
|
|
|
| 869 |
|
| 870 |
gr.HTML(
|
| 871 |
"""
|
| 872 |
+
<div class="studio-footer">
|
| 873 |
ساختهشده با ❤️ توسط <b>Ali Jahani</b> |
|
| 874 |
+
🌐 وبسایت: <a href="https://jahaniwww.com" target="_blank">jahaniwww.com</a> |
|
| 875 |
+
✈️ کانال تلگرام: <a href="https://t.me/tarfandoonchannel" target="_blank">@tarfandoonchannel</a>
|
| 876 |
</div>
|
| 877 |
"""
|
| 878 |
)
|
|
|
|
| 883 |
inputs=[in_img, num_colors, show_grid],
|
| 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,
|
| 894 |
+
color_recipe_html,
|
| 895 |
color_dropdown,
|
| 896 |
attn_out,
|
| 897 |
val_out,
|
|
|
|
| 900 |
|
| 901 |
step_slider.change(
|
| 902 |
fn=render_slide,
|
| 903 |
+
inputs=[step_slider, zone_chk, studio_state],
|
| 904 |
outputs=[slide_img, slide_guide, step_slider],
|
| 905 |
)
|
| 906 |
+
zone_chk.change(
|
| 907 |
fn=render_slide,
|
| 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,
|