tarfandoon commited on
Commit
8951f79
·
verified ·
1 Parent(s): 4d428bb

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +201 -0
  2. requirements.txt +11 -0
app.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ hf_space/app.py
3
+ Standard Hugging Face Spaces App & Local Runner for PaintPathNet!
4
+
5
+ Works in TWO ways with zero code changes:
6
+ 1. Locally on your laptop (after downloading from Kaggle/Drive):
7
+ python hf_space/app.py --model-dir ./hf_model
8
+ or:
9
+ python hf_space/app.py --ckpt ./paintpath_best.pt
10
+ 2. Directly on Hugging Face Spaces:
11
+ Set environment variable `HF_MODEL_REPO="your-username/paintpath-net"`
12
+ (or place `hf_model/` inside the Space repo) and push!
13
+ """
14
+
15
+ import argparse
16
+ import os
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import List
20
+
21
+ import cv2
22
+ import gradio as gr
23
+ import numpy as np
24
+ import torch
25
+ from PIL import Image, ImageDraw
26
+
27
+ # Support running both from project root and standalone inside a Hugging Face Space
28
+ HERE = Path(__file__).resolve().parent
29
+ ROOT = HERE.parent
30
+ for p in (str(ROOT), str(HERE)):
31
+ if p not in sys.path:
32
+ sys.path.insert(0, p)
33
+
34
+ from src.paintpath_model import PaintPathNet
35
+ from src.paintpath_stages import auto_crop_borders, generate_all_stages
36
+ from src.palette import PaletteColor, extract_physical_palette
37
+
38
+
39
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
40
+ MODEL = None
41
+ MODEL_STATUS = "Not loaded (Fallback preview mode)"
42
+
43
+
44
+ def load_paintpath_model(model_dir: str = "", ckpt_path: str = "", hf_repo: str = ""):
45
+ global MODEL, MODEL_STATUS
46
+
47
+ # 1. Standard Hugging Face local directory (`config.json` + `model.safetensors`)
48
+ if model_dir and Path(model_dir).exists():
49
+ m = PaintPathNet.from_pretrained(model_dir, pretrained=False).to(DEVICE).eval()
50
+ MODEL = m
51
+ MODEL_STATUS = f"Loaded Hugging Face model from: {model_dir} ({DEVICE})"
52
+ return
53
+
54
+ # 2. Hugging Face Hub Repo ID (for Hugging Face Spaces!)
55
+ if hf_repo:
56
+ m = PaintPathNet.from_pretrained(hf_repo, pretrained=False).to(DEVICE).eval()
57
+ MODEL = m
58
+ MODEL_STATUS = f"Loaded Hugging Face Hub model: {hf_repo} ({DEVICE})"
59
+ return
60
+
61
+ # 3. Direct PyTorch checkpoint (`paintpath_best.pt`)
62
+ if ckpt_path and Path(ckpt_path).exists():
63
+ m = PaintPathNet(pretrained=False).to(DEVICE)
64
+ ckpt = torch.load(ckpt_path, map_location=DEVICE)
65
+ m.load_state_dict(ckpt["model"] if "model" in ckpt else ckpt)
66
+ m.eval()
67
+ MODEL = m
68
+ MODEL_STATUS = f"Loaded checkpoint: {ckpt_path} ({DEVICE})"
69
+ return
70
+
71
+ MODEL = None
72
+ MODEL_STATUS = f"No trained weights loaded yet — running rule-based preview mode ({DEVICE})"
73
+
74
+
75
+ def add_proportion_grid(img_rgb: np.ndarray, grid_n: int = 4) -> np.ndarray:
76
+ """Overlay a subtle artist proportion grid (e.g. 4x4) on Stage 1 Sketch."""
77
+ out = img_rgb.copy()
78
+ h, w = out.shape[:2]
79
+ color = (160, 185, 220)
80
+ for i in range(1, grid_n):
81
+ y = int(round(h * i / grid_n))
82
+ x = int(round(w * i / grid_n))
83
+ cv2.line(out, (0, y), (w, y), color, 1, cv2.LINE_AA)
84
+ cv2.line(out, (x, 0), (x, h), color, 1, cv2.LINE_AA)
85
+ return out
86
+
87
+
88
+ def render_palette_card(palette: List[PaletteColor]) -> np.ndarray:
89
+ card_w, row_h = 740, 52
90
+ card_h = 44 + len(palette) * row_h
91
+ im = Image.new("RGB", (card_w, card_h), (249, 247, 243))
92
+ draw = ImageDraw.Draw(im)
93
+ draw.text((16, 12), "Your Simple Physical Palette & Tube Mixing Guide (Kubelka-Munk)", fill=(30, 30, 30))
94
+
95
+ for i, c in enumerate(palette):
96
+ y0 = 40 + i * row_h
97
+ draw.rectangle([16, y0 + 5, 82, y0 + row_h - 5], fill=c.rgb, outline=(60, 60, 60), width=1)
98
+ recipe_str = " + ".join(f"{pct}% {name}" for name, pct in c.mixing_recipe)
99
+ draw.text((96, y0 + 6), f"Color #{c.index + 1} {c.hex} ({c.proportion * 100:.1f}%)", fill=(25, 25, 25))
100
+ draw.text((96, y0 + 26), f"Mix: {recipe_str}", fill=(75, 75, 75))
101
+ return np.array(im)
102
+
103
+
104
+ @torch.no_grad()
105
+ def predict_roadmap(input_img: np.ndarray, num_colors: int, show_grid: bool, inference_size: int):
106
+ if input_img is None:
107
+ return None, None, None, None, None, "لطفاً یک تصویر نقاشی آپلود کنید."
108
+
109
+ clean = auto_crop_borders(input_img)
110
+ h, w = clean.shape[:2]
111
+ # Keep aspect ratio cleanly padded/resized to multiple of 32 for ConvNeXt U-Net
112
+ scale = inference_size / max(h, w)
113
+ nw = max(64, (int(round(w * scale)) // 32) * 32)
114
+ nh = max(64, (int(round(h * scale)) // 32) * 32)
115
+ resized = cv2.resize(clean, (nw, nh), interpolation=cv2.INTER_AREA)
116
+
117
+ palette = extract_physical_palette(resized, k=int(num_colors))
118
+ pal_card = render_palette_card(palette)
119
+
120
+ if MODEL is not None:
121
+ inp = torch.from_numpy(resized).permute(2, 0, 1).unsqueeze(0).float().to(DEVICE) / 255.0
122
+ stages_out = []
123
+ gpu_name = torch.cuda.get_device_name(0) if DEVICE.type == "cuda" else ""
124
+ use_amp = (DEVICE.type == "cuda") and ("1650" not in gpu_name and "1660" not in gpu_name)
125
+ for s_idx in range(4):
126
+ st = torch.tensor([s_idx], dtype=torch.long, device=DEVICE)
127
+ with torch.amp.autocast("cuda", enabled=use_amp, dtype=torch.float16):
128
+ pred = MODEL(inp, st)
129
+ arr = (pred[0].float().clamp(0, 1).permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8)
130
+ stages_out.append(arr)
131
+ s1, s2, s3, s4 = stages_out
132
+ else:
133
+ st_dict = generate_all_stages(resized)
134
+ s1, s2, s3, s4 = st_dict[1], st_dict[2], st_dict[3], st_dict[4]
135
+
136
+ if show_grid:
137
+ s1 = add_proportion_grid(s1, grid_n=4)
138
+
139
+ return s1, s2, s3, s4, pal_card, f"آماده شد! ({nw}x{nh}) | {MODEL_STATUS}"
140
+
141
+
142
+ def build_ui():
143
+ with gr.Blocks(title="PaintPath — AI Teaches Humans to Paint", theme=gr.themes.Soft()) as demo:
144
+ gr.Markdown(
145
+ """
146
+ # 🎨 PaintPath — AI Teaches Humans to Paint
147
+ *«همیشه انسان کار را برای هوش مصنوعی ساده می‌کند؛ این بار هوش مصنوعی هنر را برای انسان ساده می‌کند تا نقاش بشود!»*
148
+
149
+ هر نقاشی پیچیده‌ای را آپلود کن تا **PaintPathNet** آن را به **۴ مرحله ساده و قابل کشیدن با دست** + **پالت رنگ فیزیکی و فرمول ترکیب رنگ** تبدیل کند!
150
+ """
151
+ )
152
+
153
+ with gr.Row():
154
+ with gr.Column(scale=1):
155
+ in_img = gr.Image(type="numpy", label="نقاشی مورد نظرت را آپلود کن")
156
+ num_colors = gr.Slider(6, 12, value=8, step=1, label="تعداد رنگ‌های پالت ساده")
157
+ show_grid = gr.Checkbox(value=True, label="نمایش شبکه راهنمای تناسبات (4×4) روی مرحله ۱")
158
+ inf_size = gr.Slider(256, 768, value=512, step=64, label="رزولوشن خروجی (پیکسل)")
159
+ run_btn = gr.Button("✨ ساخت رودمپ نقاشی برای آماتور", variant="primary")
160
+ status = gr.Textbox(label="وضعیت مدل", value=MODEL_STATUS, interactive=False)
161
+ with gr.Column(scale=1):
162
+ pal_out = gr.Image(label="🎨 پالت رنگ فیزیکی و دستور ترکیب رنگ تیوپی")
163
+
164
+ gr.Markdown("### 🗺️ رودمپ گام‌به‌گام نقاشی (از مداد تا جزئیات نهایی)")
165
+ with gr.Row():
166
+ s1_out = gr.Image(label="مرحله ۱: اسکچ ساده و تناسبات (با مداد)")
167
+ s2_out = gr.Image(label="مرحله ۲: رنگ‌گذاری پایه و لکه‌های بزرگ (قلم پهن)")
168
+ s3_out = gr.Image(label="مرحله ۳: اضافه کردن سایه‌ها و حجم (قلم متوسط)")
169
+ s4_out = gr.Image(label="مرحله ۴: جزئیات میانی و بافت (قلم ریز)")
170
+
171
+ run_btn.click(
172
+ fn=predict_roadmap,
173
+ inputs=[in_img, num_colors, show_grid, inf_size],
174
+ outputs=[s1_out, s2_out, s3_out, s4_out, pal_out, status],
175
+ )
176
+ return demo
177
+
178
+
179
+ def main():
180
+ parser = argparse.ArgumentParser()
181
+ parser.add_argument("--model-dir", type=str, default=str(HERE / "hf_model"))
182
+ parser.add_argument("--ckpt", type=str, default="")
183
+ parser.add_argument("--hf-repo", type=str, default=os.environ.get("HF_MODEL_REPO", ""))
184
+ parser.add_argument("--port", type=int, default=7861)
185
+ args = parser.parse_args()
186
+
187
+ load_paintpath_model(args.model_dir, args.ckpt, args.hf_repo)
188
+ demo = build_ui()
189
+ demo.launch(server_name="127.0.0.1", server_port=args.port, inbrowser=True)
190
+
191
+
192
+ # Auto-load when launched directly by Hugging Face Spaces (`gradio` imports `demo`)
193
+ if os.environ.get("SPACE_ID"):
194
+ load_paintpath_model(
195
+ model_dir=str(HERE / "hf_model"),
196
+ hf_repo=os.environ.get("HF_MODEL_REPO", ""),
197
+ )
198
+ demo = build_ui()
199
+ demo.launch()
200
+ elif __name__ == "__main__":
201
+ main()
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch>=2.1.0
2
+ torchvision>=0.16.0
3
+ timm>=0.9.16
4
+ huggingface_hub>=0.23.0
5
+ safetensors>=0.4.0
6
+ opencv-python-headless>=4.8.0
7
+ scikit-learn>=1.3.0
8
+ scipy>=1.11.0
9
+ pillow>=10.0.0
10
+ numpy>=1.24.0
11
+ gradio>=4.20.0