Terrain: paint the overview and tiles at the ground's aspect (long terrains)
Browse files- projtex/backends/base.py +5 -2
- projtex/backends/qwen_space.py +2 -2
- projtex/terrain.py +28 -8
projtex/backends/base.py
CHANGED
|
@@ -12,6 +12,7 @@ import base64
|
|
| 12 |
from dataclasses import dataclass, field
|
| 13 |
from typing import Any
|
| 14 |
|
|
|
|
| 15 |
from PIL import Image
|
| 16 |
|
| 17 |
|
|
@@ -67,13 +68,15 @@ def from_data_url(url: str) -> Image.Image:
|
|
| 67 |
|
| 68 |
|
| 69 |
def fit_output(img: Image.Image, width: int, height: int) -> Image.Image:
|
| 70 |
-
"""Bring a generated image back to the request size (center-crop to aspect, then resize).
|
|
|
|
|
|
|
| 71 |
img = img.convert("RGB")
|
| 72 |
if img.size == (width, height):
|
| 73 |
return img
|
| 74 |
w, h = img.size
|
| 75 |
target = width / height
|
| 76 |
-
if abs(w / h
|
| 77 |
if w / h > target:
|
| 78 |
nw = int(round(h * target))
|
| 79 |
img = img.crop(((w - nw) // 2, 0, (w - nw) // 2 + nw, h))
|
|
|
|
| 12 |
from dataclasses import dataclass, field
|
| 13 |
from typing import Any
|
| 14 |
|
| 15 |
+
import numpy as np
|
| 16 |
from PIL import Image
|
| 17 |
|
| 18 |
|
|
|
|
| 68 |
|
| 69 |
|
| 70 |
def fit_output(img: Image.Image, width: int, height: int) -> Image.Image:
|
| 71 |
+
"""Bring a generated image back to the request size (center-crop to aspect, then resize). Within 5 % of the
|
| 72 |
+
aspect it only resizes: Spaces that follow the input's framing round its size to multiples of 32 (1024 x 384
|
| 73 |
+
came back 1664 x 640), and cropping that would shift the picture against its input."""
|
| 74 |
img = img.convert("RGB")
|
| 75 |
if img.size == (width, height):
|
| 76 |
return img
|
| 77 |
w, h = img.size
|
| 78 |
target = width / height
|
| 79 |
+
if abs(np.log((w / h) / target)) > 0.05:
|
| 80 |
if w / h > target:
|
| 81 |
nw = int(round(h * target))
|
| 82 |
img = img.crop(((w - nw) // 2, 0, (w - nw) // 2 + nw, h))
|
projtex/backends/qwen_space.py
CHANGED
|
@@ -162,8 +162,8 @@ class QwenTurboSpaceBackend(QwenSpaceBackend):
|
|
| 162 |
def generate(self, req: GenRequest) -> Image.Image:
|
| 163 |
from gradio_client import handle_file
|
| 164 |
|
| 165 |
-
side =
|
| 166 |
-
resolution = 1024 if side <=
|
| 167 |
seed = int(req.seed) % 2147483647
|
| 168 |
with tempfile.TemporaryDirectory(prefix="projtex_qwenturbo_") as td:
|
| 169 |
paths = []
|
|
|
|
| 162 |
def generate(self, req: GenRequest) -> Image.Image:
|
| 163 |
from gradio_client import handle_file
|
| 164 |
|
| 165 |
+
side = (req.width * req.height) ** 0.5 # the tiers set the pixel count: 1024 -> about 1024 x 1024
|
| 166 |
+
resolution = 1024 if side <= 1056 else 1536 if side <= 1568 else 2048 # the Space's tiers (ints)
|
| 167 |
seed = int(req.seed) % 2147483647
|
| 168 |
with tempfile.TemporaryDirectory(prefix="projtex_qwenturbo_") as td:
|
| 169 |
paths = []
|
projtex/terrain.py
CHANGED
|
@@ -1227,6 +1227,16 @@ def _srgb_to_lin(c):
|
|
| 1227 |
return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
|
| 1228 |
|
| 1229 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1230 |
def tile_layout(macro_size: int, tile: int = 1024, overlap: int = 256) -> dict:
|
| 1231 |
"""Tiles of ``tile`` px covering a ``macro_size`` map with at least ``overlap`` px of overlap."""
|
| 1232 |
if macro_size <= tile:
|
|
@@ -1422,19 +1432,26 @@ class Terrain:
|
|
| 1422 |
Image.fromarray(_u8(np.moveaxis(ch, 0, -1)), "RGBA").save(d / f"splat_{k // 4}.png")
|
| 1423 |
|
| 1424 |
# -------------------------------------------------------------------------------------- generation
|
| 1425 |
-
def _generate(self, backend, image, prompt: str, size: int, seed: int, name: str, color=None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1426 |
from PIL import Image
|
| 1427 |
|
| 1428 |
from .backends import GenRequest
|
| 1429 |
|
|
|
|
| 1430 |
if backend.name == "mock":
|
| 1431 |
return _mock_image(name, image, size, seed, color)
|
|
|
|
|
|
|
| 1432 |
img = None if image is None else Image.fromarray(_u8(image))
|
| 1433 |
if img is None and not getattr(backend, "text_to_image", False):
|
| 1434 |
-
img = Image.new("RGB", (
|
| 1435 |
prompt = "Replace this blank grey image entirely with: " + prompt
|
| 1436 |
-
out = backend.generate(GenRequest(image=img, prompt=prompt, width=
|
| 1437 |
-
return np.asarray(out.convert("RGB").resize((size, size)), np.float32) / 255
|
| 1438 |
|
| 1439 |
def _seed(self, key: str, new: bool) -> int:
|
| 1440 |
seeds = self.state.setdefault("seeds", {})
|
|
@@ -1525,12 +1542,13 @@ class Terrain:
|
|
| 1525 |
def overview(self, backend, new_seed: bool = False) -> np.ndarray:
|
| 1526 |
g = self.guide()
|
| 1527 |
W = max(self.state["width_m"], self.state["depth_m"])
|
|
|
|
| 1528 |
place = place_words(self.prm.get("prompt", ""), self.state["layers"]) or "natural terrain"
|
| 1529 |
-
prompt = overview_prompt(place, W,
|
| 1530 |
trees_allowed(self.prm.get("prompt", ""), self.state["layers"]),
|
| 1531 |
self.state.get("woods_words", "the woods"))
|
| 1532 |
self.state["overview_prompt"] = prompt
|
| 1533 |
-
ov = self._generate(backend, g, prompt, 1024, self._seed("overview", new_seed), "overview")
|
| 1534 |
self.state.pop("water_repainted_pct", None)
|
| 1535 |
(self.root / "macro" / "overview_raw.png").unlink(missing_ok=True)
|
| 1536 |
if self.prm.get("water_level") is not None: # water painted beyond the caller's shore: their land there
|
|
@@ -1561,6 +1579,7 @@ class Terrain:
|
|
| 1561 |
return {}
|
| 1562 |
W = self.weights()
|
| 1563 |
Wm = max(self.state["width_m"], self.state["depth_m"])
|
|
|
|
| 1564 |
T, stride, n = lay["tile"], lay["stride"], lay["n"]
|
| 1565 |
d = self.root / "macro" / "tiles"
|
| 1566 |
d.mkdir(parents=True, exist_ok=True)
|
|
@@ -1584,8 +1603,9 @@ class Terrain:
|
|
| 1584 |
if trees == "wooded" and not any(wooded(L) and c > 0.002 for L, c in zip(self.state["layers"], share)):
|
| 1585 |
trees = "" # no woods in this tile: no trees in it
|
| 1586 |
prompt = tile_prompt(place_words(self.prm.get("prompt", ""), self.state["layers"]) or "natural terrain",
|
| 1587 |
-
Wm * T / F,
|
| 1588 |
-
t = self._generate(backend, crop, prompt, T, self._seed(f"tile_{i}_{j}", new_seeds), f"tile_{i}_{j}"
|
|
|
|
| 1589 |
_save(d / f"tile_{i}_{j}.png", t)
|
| 1590 |
if progress:
|
| 1591 |
progress("tile", f"tile_{i}_{j}")
|
|
|
|
| 1227 |
return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
|
| 1228 |
|
| 1229 |
|
| 1230 |
+
def model_size(size: int, aspect: float) -> tuple[int, int]:
|
| 1231 |
+
"""(width, height) in multiples of 32 with about ``size`` x ``size`` pixels and ``aspect`` = width / height
|
| 1232 |
+
(at most 4:1)."""
|
| 1233 |
+
a = float(np.clip(aspect, 0.25, 4.0))
|
| 1234 |
+
if abs(np.log(a)) < 0.03:
|
| 1235 |
+
return size, size
|
| 1236 |
+
h = size / np.sqrt(a)
|
| 1237 |
+
return int(round(h * a / 32) * 32), int(round(h / 32) * 32)
|
| 1238 |
+
|
| 1239 |
+
|
| 1240 |
def tile_layout(macro_size: int, tile: int = 1024, overlap: int = 256) -> dict:
|
| 1241 |
"""Tiles of ``tile`` px covering a ``macro_size`` map with at least ``overlap`` px of overlap."""
|
| 1242 |
if macro_size <= tile:
|
|
|
|
| 1432 |
Image.fromarray(_u8(np.moveaxis(ch, 0, -1)), "RGBA").save(d / f"splat_{k // 4}.png")
|
| 1433 |
|
| 1434 |
# -------------------------------------------------------------------------------------- generation
|
| 1435 |
+
def _generate(self, backend, image, prompt: str, size: int, seed: int, name: str, color=None,
|
| 1436 |
+
aspect: float = 1.0) -> np.ndarray:
|
| 1437 |
+
"""A ``size`` px square image. ``aspect`` (ground width / depth of what the square shows) != 1: the model
|
| 1438 |
+
sees and paints it at that aspect (round crowns stay round on a long terrain), resized back to the square."""
|
| 1439 |
+
import cv2
|
| 1440 |
from PIL import Image
|
| 1441 |
|
| 1442 |
from .backends import GenRequest
|
| 1443 |
|
| 1444 |
+
gw, gh = model_size(size, aspect)
|
| 1445 |
if backend.name == "mock":
|
| 1446 |
return _mock_image(name, image, size, seed, color)
|
| 1447 |
+
if image is not None and (gw, gh) != (size, size):
|
| 1448 |
+
image = cv2.resize(image.astype(np.float32), (gw, gh), interpolation=cv2.INTER_AREA)
|
| 1449 |
img = None if image is None else Image.fromarray(_u8(image))
|
| 1450 |
if img is None and not getattr(backend, "text_to_image", False):
|
| 1451 |
+
img = Image.new("RGB", (gw, gh), (128, 128, 128))
|
| 1452 |
prompt = "Replace this blank grey image entirely with: " + prompt
|
| 1453 |
+
out = backend.generate(GenRequest(image=img, prompt=prompt, width=gw, height=gh, seed=seed, name=name))
|
| 1454 |
+
return np.asarray(out.convert("RGB").resize((size, size), Image.LANCZOS), np.float32) / 255
|
| 1455 |
|
| 1456 |
def _seed(self, key: str, new: bool) -> int:
|
| 1457 |
seeds = self.state.setdefault("seeds", {})
|
|
|
|
| 1542 |
def overview(self, backend, new_seed: bool = False) -> np.ndarray:
|
| 1543 |
g = self.guide()
|
| 1544 |
W = max(self.state["width_m"], self.state["depth_m"])
|
| 1545 |
+
aspect = self.state["width_m"] / self.state["depth_m"]
|
| 1546 |
place = place_words(self.prm.get("prompt", ""), self.state["layers"]) or "natural terrain"
|
| 1547 |
+
prompt = overview_prompt(place, W, self.state["width_m"] / model_size(1024, aspect)[0], self.state["legend"],
|
| 1548 |
trees_allowed(self.prm.get("prompt", ""), self.state["layers"]),
|
| 1549 |
self.state.get("woods_words", "the woods"))
|
| 1550 |
self.state["overview_prompt"] = prompt
|
| 1551 |
+
ov = self._generate(backend, g, prompt, 1024, self._seed("overview", new_seed), "overview", aspect=aspect)
|
| 1552 |
self.state.pop("water_repainted_pct", None)
|
| 1553 |
(self.root / "macro" / "overview_raw.png").unlink(missing_ok=True)
|
| 1554 |
if self.prm.get("water_level") is not None: # water painted beyond the caller's shore: their land there
|
|
|
|
| 1579 |
return {}
|
| 1580 |
W = self.weights()
|
| 1581 |
Wm = max(self.state["width_m"], self.state["depth_m"])
|
| 1582 |
+
aspect = self.state["width_m"] / self.state["depth_m"]
|
| 1583 |
T, stride, n = lay["tile"], lay["stride"], lay["n"]
|
| 1584 |
d = self.root / "macro" / "tiles"
|
| 1585 |
d.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 1603 |
if trees == "wooded" and not any(wooded(L) and c > 0.002 for L, c in zip(self.state["layers"], share)):
|
| 1604 |
trees = "" # no woods in this tile: no trees in it
|
| 1605 |
prompt = tile_prompt(place_words(self.prm.get("prompt", ""), self.state["layers"]) or "natural terrain",
|
| 1606 |
+
Wm * T / F, self.state["width_m"] * T / F / model_size(T, aspect)[0], present, trees)
|
| 1607 |
+
t = self._generate(backend, crop, prompt, T, self._seed(f"tile_{i}_{j}", new_seeds), f"tile_{i}_{j}",
|
| 1608 |
+
aspect=aspect)
|
| 1609 |
_save(d / f"tile_{i}_{j}.png", t)
|
| 1610 |
if progress:
|
| 1611 |
progress("tile", f"tile_{i}_{j}")
|