CaveWorld3D / project /scripts /cache_cave_outpaint.py
xiaojie06's picture
Archive CaveWorld3D project files 路 5
1d15e3f verified
Raw History Blame Contribute Delete
4.43 kB
"""Cache source-only Qwen conditioning separately from real supervision and preserve the sensor aspect ratio."""
from pathlib import Path
import sys
import time
import cv2
import torch
from PIL import Image
import numpy as np
from inventory_cave_outpaint import read, write
from cave_outpaint_inputs import inputs, model_shape, rgb, mask
from train_measured_panorama import pack
from train_field_perspective import pipeline
MODELS = Path("/mnt/datadisk0/xj/models")
PREFIX = (
"Image 1 is the supplied camera photograph. Image 2 shows exactly where it belongs in the expanded camera view. "
"Neutral gray in image 2 is unobserved. Produce a single continuous full-frame field photograph. "
)
def save(p, v):
p.parent.mkdir(parents=True, exist_ok=True)
tmp = p.with_suffix(".part")
torch.save(v, tmp)
tmp.replace(p)
def load(p):
return torch.load(p, map_location="cpu", weights_only=True)
def wait(p):
while not p.is_file():
time.sleep(3)
return p
def enc(pipe, im, w, h):
return pack(pipe, Image.fromarray(im), w, h)[0]
@torch.inference_mode()
def condition(pipe, r, v, edge):
w, h = model_shape(v["guide"], edge)
qw, qh = model_shape(v["query"], 336)
im = Image.fromarray(v["query"]).resize((qw, qh), Image.Resampling.LANCZOS)
cw, ch = model_shape(v["guide"], 352)
gi = Image.fromarray(v["guide"]).resize((cw, ch), Image.Resampling.LANCZOS)
text, att = pipe.encode_prompt(
image=[im, gi],
prompt=PREFIX + r["prompt"],
device="cuda",
num_images_per_prompt=1,
)
a, sa = pack(pipe, im, qw, qh)
b, sb = pack(pipe, gi, cw, ch)
anc, shape = pack(pipe, Image.fromarray(v["init"]), w, h)
known = cv2.erode(v["known"].astype("u1"), np.ones((5, 5), "u1")).astype("f4")
km = cv2.resize(known, (shape[2], shape[1]), interpolation=cv2.INTER_AREA)
return dict(
text=text.cpu(),
attention=att.cpu(),
ref=torch.cat([a, b], 1),
shapes=[sa, sb],
shape=shape,
anchor=anc,
known_latent=enc(pipe, v["guide"], w, h),
keep=torch.from_numpy((km > 0.97).reshape(1, -1, 1)),
width=w,
height=h,
)
@torch.inference_mode()
def main(root):
cv2.setNumThreads(2)
rows = read(wait(root / "evidence/cases.json"))
pipe = pipeline(MODELS)
edge = 512
for i, r in enumerate(rows):
p = root / "cache/condition" / (r["case"] + ".pt")
label = root / "cache/labels" / (r["case"] + ".pt")
if not (label.is_file() and p.is_file()):
v = inputs(root, r)
torch.manual_seed(5442)
c = condition(pipe, r, v, edge)
save(p, c)
path = root / "cases" / r["case"]
gt = rgb(path / "truth.png")
novel = mask(path / "mask.png")
w, h = c["width"], c["height"]
s = c["shape"]
gt_sm = cv2.resize(gt, (w, h), interpolation=cv2.INTER_AREA)
m = cv2.resize(novel.astype("f4"), (w, h), interpolation=cv2.INTER_AREA)
distance = cv2.distanceTransform((~v["known"]).astype("u1"), cv2.DIST_L2, 5)
dist = cv2.resize(
distance, (s[2], s[1]), interpolation=cv2.INTER_AREA
) / min(novel.shape)
yy = (gt_sm / 255) @ np.array([0.2126, 0.7152, 0.0722])
illum = 1 + 0.6 * (yy < 0.2) + 1.0 * (yy > 0.70)
importance = (
cv2.resize(
(m * illum).astype("f4"), (s[2], s[1]), interpolation=cv2.INTER_AREA
)
* (1 + 0.55 * (dist < 0.09) + 0.25 * (dist > 0.25))
+ 0.035
)
save(
label,
dict(
clean=enc(pipe, gt, w, h),
rgb=torch.from_numpy(gt_sm),
outside=torch.from_numpy(m.astype("f4")),
weight=torch.from_numpy(importance.reshape(1, -1).astype("f4")),
),
)
if i % 25 == 0:
print("cache", i + 1, len(rows), flush=True)
write(
root / "cache/complete.json",
dict(
cases=len(rows),
long_edge=edge,
base="Qwen-Image-Edit-2509",
conditioning="query and projected known pixels only",
separate_labels=True,
),
)
if __name__ == "__main__":
main(Path(sys.argv[1]))