webcomic-background-mcp 3.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- webcomic_background_mcp/__init__.py +6 -0
- webcomic_background_mcp/_home.py +11 -0
- webcomic_background_mcp/citygen.py +366 -0
- webcomic_background_mcp/klein.py +342 -0
- webcomic_background_mcp/props.py +242 -0
- webcomic_background_mcp/server.py +635 -0
- webcomic_background_mcp/setup_models.py +111 -0
- webcomic_background_mcp/test_client.py +19 -0
- webcomic_background_mcp/test_generate.py +23 -0
- webcomic_background_mcp/tools/__init__.py +1 -0
- webcomic_background_mcp/tools/fix_green.py +43 -0
- webcomic_background_mcp/tools/grade.py +134 -0
- webcomic_background_mcp/tools/inpaint_region.py +80 -0
- webcomic_background_mcp/tools/letter_plaque.py +94 -0
- webcomic_background_mcp/tools/make_depth.py +56 -0
- webcomic_background_mcp/tools/make_sketch.py +131 -0
- webcomic_background_mcp/tools/parallax.py +132 -0
- webcomic_background_mcp/world.py +307 -0
- webcomic_background_mcp-3.1.0.dist-info/METADATA +340 -0
- webcomic_background_mcp-3.1.0.dist-info/RECORD +23 -0
- webcomic_background_mcp-3.1.0.dist-info/WHEEL +5 -0
- webcomic_background_mcp-3.1.0.dist-info/entry_points.txt +2 -0
- webcomic_background_mcp-3.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
"""FLUX 3 Image Klein -- the background server's rendering model since v3.0.0.
|
|
2
|
+
|
|
3
|
+
Replaces FLUX.1-dev (GGUF unet + manwha_style LoRA + ControlNet Union Pro 2 +
|
|
4
|
+
Kontext), which the character-panel server had already left. Plates and
|
|
5
|
+
figures now come from the same model, for the same reason SD1.5 went in
|
|
6
|
+
v2.0.0: a plate from one model under figures from another reads as a
|
|
7
|
+
composite.
|
|
8
|
+
|
|
9
|
+
It runs on its OWN ComfyUI (v0.41+, port 8189), the same install the
|
|
10
|
+
character-panel server uses -- one Klein ComfyUI serves both. The main
|
|
11
|
+
ComfyUI (v0.25.1, port 8188) is left alone: LTX, the music model and matting
|
|
12
|
+
run there through add-ons never tested on v0.41.
|
|
13
|
+
|
|
14
|
+
What replaced each FLUX.1 part, measured 2026-10-17 on this server's own cases:
|
|
15
|
+
|
|
16
|
+
* STYLE. FLUX.1 LoRAs cannot load in Klein (0 of manwha_style's 494 layers
|
|
17
|
+
exist). The look comes from a positive style tail instead -- the same
|
|
18
|
+
sentence the character server uses, so plates and figures match. On the
|
|
19
|
+
world bible's own prompts (a canal lane, a mountain stair) it held crisp
|
|
20
|
+
inked cel shading at eye level AND on a summit vista, the shot
|
|
21
|
+
that pulled FLUX.1 photoreal.
|
|
22
|
+
|
|
23
|
+
* CONTROLNET -> SKETCH AS REFERENCE. There is no Klein ControlNet. The
|
|
24
|
+
white-on-black composition sketch is passed as reference image 1 with a
|
|
25
|
+
lead sentence saying what it is. On the 3D bike-row sketch Klein put all
|
|
26
|
+
four bicycles and the bollard exactly where the sketch drew them -- real
|
|
27
|
+
bicycles, the case FLUX.1 needed the 3D proxy pipeline AND ControlNet for.
|
|
28
|
+
Two wording traps, both measured:
|
|
29
|
+
- "Render it as a finished, fully colored scene" came back PHOTOREAL.
|
|
30
|
+
Saying "draw ... as a manhwa background illustration" fixed it.
|
|
31
|
+
- The sketch's black was read as EMPTY SPACE: a city floated in a gray
|
|
32
|
+
void until the lead said the black areas are ground, walls and sky.
|
|
33
|
+
SKETCH_LEAD below is the wording that passed both.
|
|
34
|
+
|
|
35
|
+
* LOCATION (img2img at 0.65 denoise) -> LOCATION AS REFERENCE. The canonical
|
|
36
|
+
plate is reference image 1. The round library tower, asked for "the same
|
|
37
|
+
room from a new angle, looking up toward the gallery and dome", kept its
|
|
38
|
+
curved shelving, lattice gallery and radial coffered dome from a camera the
|
|
39
|
+
canon never showed. FLUX.1's img2img could only nudge the canon's own
|
|
40
|
+
framing (bible note 11: a clearing could not be got out of a path plate).
|
|
41
|
+
|
|
42
|
+
* KONTEXT -> edit_region(). Klein redraws the WHOLE frame even for a boxed
|
|
43
|
+
edit (character server measured 18.5 of mean change outside the box), so a
|
|
44
|
+
region edit composites only its region back -- the change outside the box
|
|
45
|
+
is exactly zero, which Kontext never managed.
|
|
46
|
+
|
|
47
|
+
* SPEED. 14 s per plate text-to-image, 30-100 s with a reference, on the 6 GB
|
|
48
|
+
card. FLUX.1 took ~225 s and timed out the MCP call on 1152x704 interiors.
|
|
49
|
+
|
|
50
|
+
The 9B prompt upsampler in BFL's repo is left OFF: it rewrites the prompt
|
|
51
|
+
before generation, and every prompting rule in this server assumes the prompt
|
|
52
|
+
the model sees is the one that was written.
|
|
53
|
+
"""
|
|
54
|
+
import io
|
|
55
|
+
import json
|
|
56
|
+
import os
|
|
57
|
+
import subprocess
|
|
58
|
+
import time
|
|
59
|
+
import uuid
|
|
60
|
+
|
|
61
|
+
import requests
|
|
62
|
+
from PIL import Image, ImageFilter
|
|
63
|
+
|
|
64
|
+
import _home
|
|
65
|
+
|
|
66
|
+
KLEIN_URL = os.environ.get("WEBCOMIC_BG_KLEIN_URL", "http://127.0.0.1:8189")
|
|
67
|
+
KLEIN_DIR = os.environ.get("WEBCOMIC_BG_KLEIN_DIR", r"C:\AI\ComfyUI_flux3")
|
|
68
|
+
KLEIN_PORT = KLEIN_URL.rsplit(":", 1)[-1].split("/")[0]
|
|
69
|
+
LAUNCH_TIMEOUT = int(os.environ.get("WEBCOMIC_BG_KLEIN_LAUNCH_TIMEOUT", "180"))
|
|
70
|
+
# Set WEBCOMIC_BG_AUTOLAUNCH=0 to require a manually started Klein ComfyUI.
|
|
71
|
+
AUTOLAUNCH = os.environ.get("WEBCOMIC_BG_AUTOLAUNCH", "1").lower() not in ("0", "false", "no", "")
|
|
72
|
+
|
|
73
|
+
# BFL's black-forest-labs/flux-3-image-klein-comfy files. INT8, not FP8: an
|
|
74
|
+
# Ampere card has INT8 tensor cores and no native FP8; NVFP4 needs Blackwell.
|
|
75
|
+
# The _sd_ file is the step-distilled model.
|
|
76
|
+
MODEL = os.environ.get("WEBCOMIC_BG_KLEIN_MODEL", "flux3_image_klein_sd_int8_convrot.safetensors")
|
|
77
|
+
TEXT_ENCODER = os.environ.get("WEBCOMIC_BG_KLEIN_TE", "qwen3vl_4b_int8_convrot.safetensors")
|
|
78
|
+
VAE = os.environ.get("WEBCOMIC_BG_KLEIN_VAE", "flux2-vae.safetensors")
|
|
79
|
+
|
|
80
|
+
# Identical to the character server's tail on purpose: plates and figures are
|
|
81
|
+
# meant to look like one drawing. Stated as positives -- Klein, like FLUX.1,
|
|
82
|
+
# does nothing useful with negatives.
|
|
83
|
+
STYLE = ("Manhwa illustration, crisp black outlines and hard-edged flat color, "
|
|
84
|
+
"every edge in sharp focus.")
|
|
85
|
+
|
|
86
|
+
# Where each project's style.txt lives: the same folder as the world bible. A clone keeps it beside the code as it
|
|
87
|
+
# always has; installed, it follows world.WORLD_ROOT (WEBCOMIC_BG_WORLD, else ~/webcomic-background-mcp/world).
|
|
88
|
+
WORLD_ROOT = (os.path.join(_home.BASE, "world") if _home.IN_REPO else
|
|
89
|
+
os.environ.get("WEBCOMIC_BG_WORLD", os.path.join(_home.HOME, "world")))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def style_for(project: str | None) -> str:
|
|
93
|
+
"""The style sentence appended to every prompt for `project`: world/<project>/style.txt if the project
|
|
94
|
+
sets its own look (gitignored with that project's world bible), else the house STYLE. Mirrors the
|
|
95
|
+
character server's style_for so a project's plates and figures share one look."""
|
|
96
|
+
if project:
|
|
97
|
+
path = os.path.join(WORLD_ROOT, project, "style.txt")
|
|
98
|
+
if os.path.isfile(path):
|
|
99
|
+
with open(path, encoding="utf-8") as f:
|
|
100
|
+
text = f.read().strip()
|
|
101
|
+
if text:
|
|
102
|
+
return text
|
|
103
|
+
return STYLE
|
|
104
|
+
|
|
105
|
+
SKETCH_LEAD = ("Image 1 is a white-on-black line drawing that fixes the exact composition, "
|
|
106
|
+
"camera angle and the outline of every object. Draw the scene it lays out as a "
|
|
107
|
+
"manhwa background illustration, keeping every object exactly where and as large "
|
|
108
|
+
"as image 1 draws it; the black areas of image 1 are not empty, fill them with "
|
|
109
|
+
"the ground, walls and sky of the scene: ")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def location_lead(name: str) -> str:
|
|
113
|
+
"""Lead for a new view of a registered place (reference image 1)."""
|
|
114
|
+
return (f"Image 1 shows {name}, an established place in this story. Keep it "
|
|
115
|
+
f"recognizably the same place, with the same architecture, materials and "
|
|
116
|
+
f"colors, while showing what follows: ")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class KleinError(RuntimeError):
|
|
120
|
+
pass
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def is_up(timeout: float = 2.0) -> bool:
|
|
124
|
+
try:
|
|
125
|
+
return requests.get(f"{KLEIN_URL}/system_stats", timeout=timeout).status_code == 200
|
|
126
|
+
except Exception:
|
|
127
|
+
return False
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def port_in_use(timeout: float = 1.0) -> bool:
|
|
131
|
+
"""Something is LISTENING on the Klein port, whether or not it answers HTTP.
|
|
132
|
+
|
|
133
|
+
A ComfyUI deep in an LTX render on this RAM-starved laptop can take longer
|
|
134
|
+
than is_up()'s 2 s to answer /system_stats. Taking that as "not running"
|
|
135
|
+
launched a SECOND ComfyUI mid-render (2026-10-24): it pinned ~13 GB of RAM
|
|
136
|
+
before dying on the database lock, and the render it starved took 3 h 12 min
|
|
137
|
+
instead of ~4. Never launch over an occupied port.
|
|
138
|
+
"""
|
|
139
|
+
import socket
|
|
140
|
+
host = KLEIN_URL.split("://", 1)[-1].split(":", 1)[0]
|
|
141
|
+
try:
|
|
142
|
+
with socket.create_connection((host, int(KLEIN_PORT)), timeout=timeout):
|
|
143
|
+
return True
|
|
144
|
+
except OSError:
|
|
145
|
+
return False
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def ensure_running() -> None:
|
|
149
|
+
"""Start the Klein ComfyUI if it is not up.
|
|
150
|
+
|
|
151
|
+
Launches the embedded interpreter directly with the working directory set:
|
|
152
|
+
the portable .bat uses relative paths and fails silently when started from
|
|
153
|
+
anywhere else. Output goes to a log beside the install, because a crash
|
|
154
|
+
here otherwise leaves no trace.
|
|
155
|
+
"""
|
|
156
|
+
if is_up():
|
|
157
|
+
return
|
|
158
|
+
if port_in_use():
|
|
159
|
+
# Busy, not down: wait for it to answer instead of starting a second one.
|
|
160
|
+
t0 = time.time()
|
|
161
|
+
while time.time() - t0 < LAUNCH_TIMEOUT:
|
|
162
|
+
if is_up(timeout=15.0):
|
|
163
|
+
return
|
|
164
|
+
time.sleep(5.0)
|
|
165
|
+
raise KleinError(f"Something holds port {KLEIN_PORT} but has not answered for {LAUNCH_TIMEOUT}s; "
|
|
166
|
+
"not launching a second ComfyUI over it.")
|
|
167
|
+
if not AUTOLAUNCH:
|
|
168
|
+
raise KleinError(f"Klein ComfyUI is not running at {KLEIN_URL} and autolaunch is off.")
|
|
169
|
+
py = os.path.join(KLEIN_DIR, "python_embeded", "python.exe")
|
|
170
|
+
if not os.path.isfile(py):
|
|
171
|
+
raise KleinError(f"Klein ComfyUI not found at {KLEIN_DIR} "
|
|
172
|
+
f"(set WEBCOMIC_BG_KLEIN_DIR; see setup_models.py).")
|
|
173
|
+
log = open(os.path.join(KLEIN_DIR, "comfy_klein.log"), "ab")
|
|
174
|
+
flags = (subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP) if os.name == "nt" else 0
|
|
175
|
+
subprocess.Popen([py, "-s", "ComfyUI/main.py", "--windows-standalone-build", "--port", KLEIN_PORT],
|
|
176
|
+
cwd=KLEIN_DIR, creationflags=flags, stdin=subprocess.DEVNULL,
|
|
177
|
+
stdout=log, stderr=log, close_fds=True)
|
|
178
|
+
t0 = time.time()
|
|
179
|
+
while time.time() - t0 < LAUNCH_TIMEOUT:
|
|
180
|
+
time.sleep(2.0)
|
|
181
|
+
if is_up():
|
|
182
|
+
return
|
|
183
|
+
raise KleinError(f"Launched Klein ComfyUI but it was not ready within {LAUNCH_TIMEOUT}s; "
|
|
184
|
+
f"see {os.path.join(KLEIN_DIR, 'comfy_klein.log')}.")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _upload(path: str) -> str:
|
|
188
|
+
if not os.path.isfile(path):
|
|
189
|
+
raise KleinError(f"Image not found: {path}")
|
|
190
|
+
with open(path, "rb") as f:
|
|
191
|
+
r = requests.post(f"{KLEIN_URL}/upload/image",
|
|
192
|
+
files={"image": (f"{uuid.uuid4().hex[:8]}_{os.path.basename(path)}", f,
|
|
193
|
+
"application/octet-stream")},
|
|
194
|
+
data={"overwrite": "true"}, timeout=60)
|
|
195
|
+
if r.status_code != 200:
|
|
196
|
+
raise KleinError(f"Upload failed ({r.status_code}): {r.text[:200]}")
|
|
197
|
+
return r.json()["name"]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _submit(graph: dict, output_node: str, timeout: int) -> bytes:
|
|
201
|
+
# The timeout counts QUEUE time as well as rendering: if the character
|
|
202
|
+
# server has a job in, this one waits behind it.
|
|
203
|
+
r = requests.post(f"{KLEIN_URL}/prompt", json={"prompt": graph}, timeout=30)
|
|
204
|
+
if r.status_code != 200:
|
|
205
|
+
raise KleinError(f"Prompt rejected ({r.status_code}): {r.text[:400]}")
|
|
206
|
+
pid = r.json()["prompt_id"]
|
|
207
|
+
t0 = time.time()
|
|
208
|
+
while time.time() - t0 < timeout:
|
|
209
|
+
time.sleep(2.0)
|
|
210
|
+
h = requests.get(f"{KLEIN_URL}/history/{pid}", timeout=30).json()
|
|
211
|
+
if pid in h:
|
|
212
|
+
st = h[pid].get("status", {})
|
|
213
|
+
if st.get("status_str") == "error":
|
|
214
|
+
raise KleinError("Render failed: " + json.dumps(st.get("messages", []))[:800])
|
|
215
|
+
outs = h[pid].get("outputs", {})
|
|
216
|
+
if output_node not in outs:
|
|
217
|
+
raise KleinError("Render produced no image (check comfy_klein.log).")
|
|
218
|
+
img = outs[output_node]["images"][0]
|
|
219
|
+
return requests.get(f"{KLEIN_URL}/view", timeout=60, params={
|
|
220
|
+
"filename": img["filename"], "subfolder": img["subfolder"], "type": img["type"]}).content
|
|
221
|
+
raise KleinError(f"Timed out after {timeout}s")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _save(data: bytes, out_dir: str, stem: str) -> str:
|
|
225
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
226
|
+
base = os.path.join(out_dir, stem)
|
|
227
|
+
path, n = base + ".png", 1
|
|
228
|
+
while os.path.exists(path):
|
|
229
|
+
path, n = f"{base}_{n}.png", n + 1
|
|
230
|
+
with open(path, "wb") as f:
|
|
231
|
+
f.write(data)
|
|
232
|
+
return path
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _png(img: Image.Image) -> bytes:
|
|
236
|
+
buf = io.BytesIO()
|
|
237
|
+
img.save(buf, "PNG")
|
|
238
|
+
return buf.getvalue()
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _snap(v: int) -> int:
|
|
242
|
+
return max(16, int(round(v / 16.0)) * 16)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def generate(prompt: str, out_dir: str, width: int = 1024, height: int = 768,
|
|
246
|
+
seed: int | None = None, refs: list[str] | None = None,
|
|
247
|
+
megapixels: float = 1.0, steps: int | None = None, stem: str = "klein",
|
|
248
|
+
add_style: bool = True, timeout: int = 900, project: str | None = None) -> str:
|
|
249
|
+
"""Render with Klein; return the saved PNG path.
|
|
250
|
+
|
|
251
|
+
refs: reference images, referred to in the prompt as "image 1", "image 2"
|
|
252
|
+
in the order given, each encoded at `megapixels` (1.0 is ~1024x1024,
|
|
253
|
+
aspect kept). The caller writes the lead that says what each one is --
|
|
254
|
+
SKETCH_LEAD or location_lead() -- because Klein does what the words say
|
|
255
|
+
a reference is for.
|
|
256
|
+
|
|
257
|
+
Graph follows ComfyUI v0.41's image_flux3_klein_distilled templates: cfg 1,
|
|
258
|
+
15 steps text-to-image with er_sde, 16 with references with euler.
|
|
259
|
+
"""
|
|
260
|
+
ensure_running()
|
|
261
|
+
width, height = _snap(width), _snap(height)
|
|
262
|
+
if seed is None:
|
|
263
|
+
seed = uuid.uuid4().int % (2 ** 31)
|
|
264
|
+
text = f"{prompt.rstrip()} {style_for(project)}" if add_style else prompt
|
|
265
|
+
refs = refs or []
|
|
266
|
+
g = {
|
|
267
|
+
"1": {"class_type": "UNETLoader", "inputs": {"unet_name": MODEL, "weight_dtype": "default"}},
|
|
268
|
+
"2": {"class_type": "CLIPLoader", "inputs": {"clip_name": TEXT_ENCODER, "type": "flux3", "device": "default"}},
|
|
269
|
+
"3": {"class_type": "VAELoader", "inputs": {"vae_name": VAE}},
|
|
270
|
+
"4": {"class_type": "CLIPTextEncode", "inputs": {"text": text, "clip": ["2", 0]}},
|
|
271
|
+
"5": {"class_type": "ConditioningZeroOut", "inputs": {"conditioning": ["4", 0]}},
|
|
272
|
+
"6": {"class_type": "EmptyFlux2LatentImage", "inputs": {"width": width, "height": height, "batch_size": 1}},
|
|
273
|
+
"9": {"class_type": "VAEDecode", "inputs": {"samples": ["8", 0], "vae": ["3", 0]}},
|
|
274
|
+
"10": {"class_type": "SaveImage", "inputs": {"images": ["9", 0], "filename_prefix": "bg_" + stem}},
|
|
275
|
+
}
|
|
276
|
+
pos, neg = ["4", 0], ["5", 0]
|
|
277
|
+
if refs:
|
|
278
|
+
ri = {"positive": ["4", 0], "negative": ["5", 0], "vae": ["3", 0],
|
|
279
|
+
"resolution": "resize", "resolution.megapixels": float(megapixels)}
|
|
280
|
+
for i, r in enumerate(refs, 1):
|
|
281
|
+
g[str(20 + i)] = {"class_type": "LoadImage", "inputs": {"image": _upload(r)}}
|
|
282
|
+
ri[f"images.image{i}"] = [str(20 + i), 0]
|
|
283
|
+
g["7"] = {"class_type": "ReferenceMultiLatent", "inputs": ri}
|
|
284
|
+
pos, neg = ["7", 0], ["7", 1]
|
|
285
|
+
g["8"] = {"class_type": "KSampler", "inputs": {
|
|
286
|
+
"model": ["1", 0], "seed": seed, "steps": steps or (16 if refs else 15), "cfg": 1.0,
|
|
287
|
+
"sampler_name": "euler" if refs else "er_sde", "scheduler": "simple",
|
|
288
|
+
"positive": pos, "negative": neg, "latent_image": ["6", 0], "denoise": 1.0}}
|
|
289
|
+
return _save(_submit(g, "10", timeout), out_dir, f"{stem}_{seed}")
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _layout(prompt: str, box, width: int, height: int) -> str:
|
|
293
|
+
"""Append one layout row the way ComfyUI's Flux3LayoutPrompt does.
|
|
294
|
+
|
|
295
|
+
Klein was trained on [ymin, xmin, ymax, xmax] rows on a 0-1000 grid. A box
|
|
296
|
+
sets an object's SIZE as well as its place -- size it to what should be
|
|
297
|
+
drawn.
|
|
298
|
+
"""
|
|
299
|
+
x0, y0, x1, y1 = box
|
|
300
|
+
row = {"id": "obj_1", "desc": "the region to redraw", "bbox": [
|
|
301
|
+
round(min(y0, y1) / height * 1000), round(min(x0, x1) / width * 1000),
|
|
302
|
+
round(max(y0, y1) / height * 1000), round(max(x0, x1) / width * 1000)]}
|
|
303
|
+
return f"{prompt.rstrip()} {json.dumps([row], ensure_ascii=False)}"
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def edit(image_path: str, instruction: str, out_dir: str, box=None, seed: int | None = None,
|
|
307
|
+
restyle: bool = False, feather: int = 14, pad: int = 24, timeout: int = 900,
|
|
308
|
+
project: str | None = None) -> str:
|
|
309
|
+
"""Edit an existing plate; the source file is never modified.
|
|
310
|
+
|
|
311
|
+
box: (x0, y0, x1, y1) in the source's pixels. Klein redraws the whole frame
|
|
312
|
+
from the source as a reference, then ONLY the box (grown by `pad`,
|
|
313
|
+
edges feathered) is composited back, so nothing outside it changes.
|
|
314
|
+
Without a box the whole redrawn frame is returned.
|
|
315
|
+
restyle: append the house style tail -- for pulling an off-style plate
|
|
316
|
+
(photoreal, painterly) back to the inked look. Leave off for content
|
|
317
|
+
edits, so the tail does not restyle what should stay.
|
|
318
|
+
"""
|
|
319
|
+
src = Image.open(image_path).convert("RGB")
|
|
320
|
+
W, H = src.size
|
|
321
|
+
text = f"Image 1 is the picture to edit. {instruction.rstrip()}"
|
|
322
|
+
if box is not None:
|
|
323
|
+
text = _layout(f"{text} Keep everything else in the picture exactly as it is.", box, W, H)
|
|
324
|
+
elif not restyle:
|
|
325
|
+
text = f"{text} Keep everything else in the picture exactly as it is."
|
|
326
|
+
raw = generate(text, out_dir, W, H, seed=seed, refs=[image_path],
|
|
327
|
+
megapixels=W * H / (1024 * 1024), stem="edit_raw",
|
|
328
|
+
add_style=restyle, timeout=timeout, project=project)
|
|
329
|
+
stem = os.path.splitext(os.path.basename(image_path))[0]
|
|
330
|
+
new = Image.open(raw).convert("RGB")
|
|
331
|
+
if new.size != (W, H):
|
|
332
|
+
new = new.resize((W, H), Image.LANCZOS)
|
|
333
|
+
if box is None:
|
|
334
|
+
out = new
|
|
335
|
+
else:
|
|
336
|
+
x0, y0, x1, y1 = [int(v) for v in box]
|
|
337
|
+
m = Image.new("L", (W, H), 0)
|
|
338
|
+
m.paste(255, (max(0, x0 - pad), max(0, y0 - pad), min(W, x1 + pad), min(H, y1 + pad)))
|
|
339
|
+
m = m.filter(ImageFilter.GaussianBlur(feather))
|
|
340
|
+
out = Image.composite(new, src, m)
|
|
341
|
+
os.remove(raw)
|
|
342
|
+
return _save(_png(out), out_dir, f"{stem}_edit")
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""
|
|
2
|
+
props.py — parametric 3D props, placed in-scene and rendered headless to a
|
|
3
|
+
ControlNet sketch (the citygen.py treatment, extended from buildings to
|
|
4
|
+
objects).
|
|
5
|
+
|
|
6
|
+
Why this exists: diffusion models are bad at *geometry* — rows of repeated
|
|
7
|
+
objects (bicycles, carts, market stalls) come out fused, cropped, or mutated
|
|
8
|
+
when the model has to invent their structure. Buildings never had this problem
|
|
9
|
+
here because citygen.py hands SD a projection-correct sketch and lets it paint.
|
|
10
|
+
Props get the same deal: real 3D meshes, real camera, real occlusion via the
|
|
11
|
+
painter's algorithm, one coherent Canny sketch — SD only paints.
|
|
12
|
+
|
|
13
|
+
World scale matches citygen.py: 1 unit ≈ 0.37 m, a standing adult ≈ 4.6 units.
|
|
14
|
+
A bicycle wheel here is r=0.92 units ≈ 0.34 m (a 26" wheel), saddle ≈ 2.2
|
|
15
|
+
units ≈ 0.8 m. Props therefore drop into city scenes at the correct size.
|
|
16
|
+
|
|
17
|
+
Pipeline: build_props(objects) [+ build_shelter] -> auto_camera -> lineart
|
|
18
|
+
-> Canny sketch -> workflow.generate paints it.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import math
|
|
22
|
+
import os
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
import cv2
|
|
26
|
+
|
|
27
|
+
import citygen as cg
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# ------------------------------------------------------------- mesh helpers --
|
|
31
|
+
def _mesh(v, f, gray):
|
|
32
|
+
return cg._Mesh(np.array(v, dtype=np.float64), f, gray)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _tube(p0, p1, width, z=0.0):
|
|
36
|
+
"""Thin quad joining two (x, y) points in a prop's local X-Y plane."""
|
|
37
|
+
x0, y0 = p0
|
|
38
|
+
x1, y1 = p1
|
|
39
|
+
dx, dy = x1 - x0, y1 - y0
|
|
40
|
+
length = math.hypot(dx, dy) or 1e-6
|
|
41
|
+
px, py = -dy / length * width / 2, dx / length * width / 2
|
|
42
|
+
v = [[x0 + px, y0 + py, z], [x1 + px, y1 + py, z],
|
|
43
|
+
[x1 - px, y1 - py, z], [x0 - px, y0 - py, z]]
|
|
44
|
+
return v, [(0, 1, 2, 3)]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _disc(cx, cy, r, n=28, z=0.0):
|
|
48
|
+
ang = np.linspace(0, 2 * math.pi, n, endpoint=False)
|
|
49
|
+
v = [[cx + r * math.cos(a), cy + r * math.sin(a), z] for a in ang]
|
|
50
|
+
return v, [tuple(range(n))]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# ------------------------------------------------------------------ bicycle --
|
|
54
|
+
def build_bicycle(index: int = 0, r: float = 0.92):
|
|
55
|
+
"""One parked bicycle, local space: standing on y=0, its side profile in
|
|
56
|
+
the X-Y plane (a flat cutout — correct for a sketch pass), facing -X.
|
|
57
|
+
|
|
58
|
+
Geometry tuned against a real road-bike reference across a full session of
|
|
59
|
+
A/B renders (see CHANGELOG v1.8.0): thin tire (rim at 0.82r — a fat ring
|
|
60
|
+
reads as a motorcycle/millstone), true diamond frame with fork, chain stay
|
|
61
|
+
and seat stay, saddle, and a straight T-bar handlebar mounted HIGHER than
|
|
62
|
+
the saddle (a curved drop-bar hook kept getting painted as a second
|
|
63
|
+
saddle).
|
|
64
|
+
|
|
65
|
+
`index` offsets this bike's flat grays so neighbouring bikes in a row stay
|
|
66
|
+
separable at the Canny stage instead of fusing — the same per-mesh-shade
|
|
67
|
+
trick citygen uses for adjacent buildings.
|
|
68
|
+
"""
|
|
69
|
+
d = 1.4 * r # half wheelbase
|
|
70
|
+
tube_w = 0.09 * r
|
|
71
|
+
rear_hub = (-d, r)
|
|
72
|
+
front_hub = (d, r)
|
|
73
|
+
bb = (-d * 0.12, r * 0.45) # bottom bracket
|
|
74
|
+
seat_top = (-d * 0.62, r * 1.95)
|
|
75
|
+
head_bottom = (d * 0.72, r * 1.05)
|
|
76
|
+
head_top = (d * 0.62, r * 1.62)
|
|
77
|
+
handle = (d * 0.95, r * 2.15) # above saddle height
|
|
78
|
+
|
|
79
|
+
base = cg._gray(index * 2 + 1)
|
|
80
|
+
tire_g = max(12, base - 35)
|
|
81
|
+
rim_g = min(230, base + 25)
|
|
82
|
+
frame_g = max(15, base - 15)
|
|
83
|
+
|
|
84
|
+
meshes = []
|
|
85
|
+
for hub in (rear_hub, front_hub):
|
|
86
|
+
meshes.append(_mesh(*_disc(hub[0], hub[1], r), gray=tire_g))
|
|
87
|
+
meshes.append(_mesh(*_disc(hub[0], hub[1], r * 0.82, z=-0.01), gray=rim_g))
|
|
88
|
+
meshes.append(_mesh(*_disc(hub[0], hub[1], r * 0.08, z=-0.02), gray=max(10, tire_g - 10)))
|
|
89
|
+
|
|
90
|
+
for p0, p1 in [(bb, seat_top), (seat_top, head_top), (head_top, bb),
|
|
91
|
+
(bb, head_bottom), (head_bottom, head_top),
|
|
92
|
+
(seat_top, rear_hub), (bb, rear_hub),
|
|
93
|
+
(head_bottom, front_hub)]:
|
|
94
|
+
meshes.append(_mesh(*_tube(p0, p1, tube_w), gray=frame_g))
|
|
95
|
+
|
|
96
|
+
sx, sy = seat_top # saddle
|
|
97
|
+
meshes.append(_mesh(*_tube((sx - 0.22 * r, sy + 0.1 * r),
|
|
98
|
+
(sx + 0.12 * r, sy + 0.1 * r), 0.16 * r), gray=frame_g))
|
|
99
|
+
hx, hy = handle # stem + straight T-bar
|
|
100
|
+
bar_half = r * 0.42
|
|
101
|
+
meshes.append(_mesh(*_tube(head_top, handle, tube_w), gray=frame_g))
|
|
102
|
+
meshes.append(_mesh(*_tube((hx - bar_half, hy), (hx + bar_half, hy),
|
|
103
|
+
tube_w * 0.85), gray=frame_g))
|
|
104
|
+
meshes.append(_mesh(*_disc(bb[0], bb[1], r * 0.16, z=-0.015), gray=frame_g)) # crank
|
|
105
|
+
meshes.append(_mesh(*_tube(bb, (bb[0] + 0.22 * r, bb[1] - 0.1 * r), 0.08 * r), gray=frame_g))
|
|
106
|
+
|
|
107
|
+
for m in meshes: # face -X (matches reference)
|
|
108
|
+
m.v[:, 0] *= -1
|
|
109
|
+
return meshes
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
PROPS = {"bicycle": build_bicycle}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# ---------------------------------------------------------------- placement --
|
|
116
|
+
def place(meshes, x=0.0, z=0.0, yaw_deg=0.0, scale=1.0):
|
|
117
|
+
"""Copy prop meshes into world space: scale, rotate about Y, translate."""
|
|
118
|
+
yaw = math.radians(yaw_deg)
|
|
119
|
+
c, s = math.cos(yaw), math.sin(yaw)
|
|
120
|
+
out = []
|
|
121
|
+
for m in meshes:
|
|
122
|
+
v = m.v.copy() * scale
|
|
123
|
+
xr = v[:, 0] * c - v[:, 2] * s
|
|
124
|
+
zr = v[:, 0] * s + v[:, 2] * c
|
|
125
|
+
v[:, 0] = xr + x
|
|
126
|
+
v[:, 2] = zr + z
|
|
127
|
+
out.append(cg._Mesh(v, m.f, m.gray))
|
|
128
|
+
return out
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def build_props(objects):
|
|
132
|
+
"""objects: [{"type": "bicycle", "x": 0, "z": 0, "yaw": 0, "scale": 1}, ...]
|
|
133
|
+
Unknown types raise ValueError listing what exists."""
|
|
134
|
+
meshes = []
|
|
135
|
+
for i, ob in enumerate(objects):
|
|
136
|
+
kind = ob.get("type", "bicycle")
|
|
137
|
+
if kind not in PROPS:
|
|
138
|
+
raise ValueError(f"unknown prop '{kind}'; available: {', '.join(PROPS)}")
|
|
139
|
+
prop = PROPS[kind](index=i)
|
|
140
|
+
meshes += place(prop, ob.get("x", 0.0), ob.get("z", 0.0),
|
|
141
|
+
ob.get("yaw", 0.0), ob.get("scale", 1.0))
|
|
142
|
+
return meshes
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def bike_row(n=4, spacing=2.2, x=0.0, z0=0.0, yaw=0.0, jitter=4.0):
|
|
146
|
+
"""Convenience: a parked row — n bicycles side by side along Z, real-rack
|
|
147
|
+
spacing (~0.8 m). `jitter` alternates a few degrees of yaw per bike: real
|
|
148
|
+
parked bikes are never perfectly parallel, and it guarantees no flat
|
|
149
|
+
cutout is ever seen exactly edge-on (which renders as a sliver — flat
|
|
150
|
+
props need the camera ≥ ~25° off their plane, see auto_camera)."""
|
|
151
|
+
return [{"type": "bicycle", "x": x, "z": z0 + i * spacing,
|
|
152
|
+
"yaw": yaw + (jitter if i % 2 else -jitter)}
|
|
153
|
+
for i in range(n)]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
# ------------------------------------------------------------------ shelter --
|
|
157
|
+
def build_shelter(meshes_bbox, gray_wall=70, gray_post=50, gray_roof=60):
|
|
158
|
+
"""A simple carport over the props: back wall, posts, flat roof slab.
|
|
159
|
+
Deliberately crude — SD paints the gothic detail; this only gives the
|
|
160
|
+
sketch believable large forms. Sized from the props' bounding box."""
|
|
161
|
+
pts_min, pts_max = meshes_bbox
|
|
162
|
+
x0, z0, z1 = pts_max[0] + 1.2, pts_min[2] - 2.5, pts_max[2] + 2.5
|
|
163
|
+
depth = z1 - z0
|
|
164
|
+
meshes = []
|
|
165
|
+
wv, wf = cg._box((x0 + 1.0), 0, (z0 + z1) / 2, 2.0, 9.5, depth + 4) # back wall
|
|
166
|
+
meshes.append(cg._Mesh(wv, wf, gray_wall))
|
|
167
|
+
n_posts = max(2, int(depth // 5))
|
|
168
|
+
for i in range(n_posts + 1):
|
|
169
|
+
pz = z0 + depth * i / n_posts
|
|
170
|
+
pv, pf = cg._box(pts_min[0] - 0.8, 0, pz, 0.55, 7.0, 0.55) # posts
|
|
171
|
+
meshes.append(cg._Mesh(pv, pf, gray_post))
|
|
172
|
+
rv, rf = cg._box((x0 + pts_min[0] - 0.8) / 2, 7.0, (z0 + z1) / 2, # roof slab
|
|
173
|
+
(x0 - pts_min[0]) + 2.6, 0.5, depth + 2)
|
|
174
|
+
meshes.append(cg._Mesh(rv, rf, gray_roof))
|
|
175
|
+
return meshes
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# ------------------------------------------------------------------- camera --
|
|
179
|
+
def auto_camera(meshes, width, height, angle_deg=28.0, elev_deg=9.0,
|
|
180
|
+
fov=42.0, fill=0.82, frame_on=None):
|
|
181
|
+
"""Fit a camera so every vertex of `frame_on` (default: all meshes) lands
|
|
182
|
+
inside the frame with breathing room. This is what prevents the clipped-
|
|
183
|
+
wheel failure: framing is computed from the geometry, never eyeballed.
|
|
184
|
+
|
|
185
|
+
angle_deg: yaw of the camera around the subject (0 = looking straight at
|
|
186
|
+
the props' side profiles from -X; positive swings toward +Z, a 3/4 view).
|
|
187
|
+
fill: max fraction of each half-axis of the frame the subject may occupy.
|
|
188
|
+
"""
|
|
189
|
+
frame_meshes = frame_on if frame_on is not None else meshes
|
|
190
|
+
pts = np.vstack([m.v for m in frame_meshes])
|
|
191
|
+
center = (pts.min(axis=0) + pts.max(axis=0)) / 2
|
|
192
|
+
yaw, el = math.radians(angle_deg), math.radians(elev_deg)
|
|
193
|
+
direction = np.array([-math.cos(yaw) * math.cos(el),
|
|
194
|
+
math.sin(el),
|
|
195
|
+
-math.sin(yaw) * math.cos(el)]) # centroid -> camera
|
|
196
|
+
dist = 6.0
|
|
197
|
+
cam = None
|
|
198
|
+
for _ in range(60):
|
|
199
|
+
pos = center + direction * dist
|
|
200
|
+
cam = {"pos": tuple(pos), "look": tuple(center), "fov": fov}
|
|
201
|
+
p, r, u, f, focal = cg._cam_basis(cam, width, height)
|
|
202
|
+
rel = pts - p
|
|
203
|
+
x, y, z = rel @ r, rel @ u, rel @ f
|
|
204
|
+
if np.any(z < 1.0):
|
|
205
|
+
dist *= 1.25
|
|
206
|
+
continue
|
|
207
|
+
sx = focal * x / z
|
|
208
|
+
sy = focal * y / z
|
|
209
|
+
if (np.abs(sx).max() <= (width / 2) * fill and
|
|
210
|
+
np.abs(sy).max() <= (height / 2) * fill):
|
|
211
|
+
return cam
|
|
212
|
+
dist *= 1.12
|
|
213
|
+
return cam
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
# ----------------------------------------------------------------- pipeline --
|
|
217
|
+
def prop_sketch(out_dir, objects, setting="shelter", width=1344, height=1008,
|
|
218
|
+
angle_deg=28.0, elev_deg=9.0, fov=42.0,
|
|
219
|
+
low=60, high=140, tag="props"):
|
|
220
|
+
"""Build props (+ optional shelter) -> auto-framed lineart -> Canny sketch.
|
|
221
|
+
Returns (sketch_path, lineart_path). The camera frames the PROPS; the
|
|
222
|
+
shelter may run past the frame edges (walls always do)."""
|
|
223
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
224
|
+
prop_meshes = build_props(objects)
|
|
225
|
+
meshes = list(prop_meshes)
|
|
226
|
+
if setting == "shelter":
|
|
227
|
+
pts = np.vstack([m.v for m in prop_meshes])
|
|
228
|
+
meshes += build_shelter((pts.min(axis=0), pts.max(axis=0)))
|
|
229
|
+
elif setting not in (None, "", "none"):
|
|
230
|
+
raise ValueError(f"unknown setting '{setting}'; use 'shelter' or 'none'")
|
|
231
|
+
|
|
232
|
+
cam = auto_camera(meshes, width, height, angle_deg, elev_deg, fov,
|
|
233
|
+
frame_on=prop_meshes)
|
|
234
|
+
lineart = cg.render_lineart(meshes, camera=cam, width=width, height=height)
|
|
235
|
+
line_path = os.path.join(out_dir, f"{tag}_lineart.png")
|
|
236
|
+
cv2.imwrite(line_path, lineart)
|
|
237
|
+
|
|
238
|
+
blurred = cv2.GaussianBlur(lineart, (3, 3), 0)
|
|
239
|
+
edges = cv2.Canny(blurred, low, high)
|
|
240
|
+
sketch_path = os.path.join(out_dir, f"{tag}_sketch.png")
|
|
241
|
+
cv2.imwrite(sketch_path, edges)
|
|
242
|
+
return sketch_path, line_path
|