asc-eye-v1 / asc_eye /encode_image.py
tim-scrypted's picture
Publish asc-eye_v1 inference package (weights, encode scripts, promo, splash)
90bec74 verified
Raw History Blame Contribute Delete
8.57 kB
#!/usr/bin/env python3
"""Encode an image to ASCII (or CP437) with a trained PatchToGlyph checkpoint; emit text + PNG."""
from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from .preprocess import to_luma01, tone_stretch
from .glyph_bank import (
BORDER,
CELL_H,
CELL_W,
WIN_H,
WIN_W,
GlyphBank,
)
from .model import PatchToGlyph
def _target_hw(h: int, w: int, width_cells: int | None) -> tuple[int, int]:
if width_cells is not None:
target_w = max(CELL_W, width_cells * CELL_W)
else:
# Default: ~120 cells wide, or native if smaller
target_w = min(w, 120 * CELL_W)
target_w = max(CELL_W * 8, (target_w // CELL_W) * CELL_W)
nh = max(CELL_H, int(round(h * (target_w / w))))
nh = (nh // CELL_H) * CELL_H
return nh, target_w
def prepare_luma(path: Path, width_cells: int | None) -> np.ndarray:
img = Image.open(path).convert("RGB")
y = tone_stretch(to_luma01(img))
h, w = y.shape
nh, target_w = _target_hw(h, w, width_cells)
pil = Image.fromarray((y * 255).clip(0, 255).astype(np.uint8), mode="L")
pil = pil.resize((target_w, nh), Image.Resampling.LANCZOS)
return np.asarray(pil, dtype=np.float32) / 255.0
def prepare_luma_rgb(
img: Image.Image,
width_cells: int,
) -> tuple[np.ndarray, np.ndarray]:
"""Tone-stretched luma for the model + RGB resized to the same cell grid."""
rgb_img = img.convert("RGB")
y = tone_stretch(to_luma01(rgb_img))
h, w = y.shape
nh, target_w = _target_hw(h, w, width_cells)
luma = Image.fromarray((y * 255).clip(0, 255).astype(np.uint8), mode="L")
luma = luma.resize((target_w, nh), Image.Resampling.LANCZOS)
rgb = rgb_img.resize((target_w, nh), Image.Resampling.LANCZOS)
y_arr = np.asarray(luma, dtype=np.float32) / 255.0
rgb_arr = np.asarray(rgb, dtype=np.float32) / 255.0
return y_arr, rgb_arr
def cell_mean_colors(
rgb: np.ndarray,
sat_boost: float = 1.35,
sat_lift: float = 0.04,
) -> np.ndarray:
"""Per-cell mean RGB with mild HSV saturation boost (reads better on black).
Returns [rows, cols, 3] float32 in [0, 1].
"""
H, W, _ = rgb.shape
rows, cols = H // CELL_H, W // CELL_W
# reshape → mean over pixels in each cell
tiles = rgb.reshape(rows, CELL_H, cols, CELL_W, 3).mean(axis=(1, 3))
# saturation boost in HSV
hsv = np.asarray(
Image.fromarray((tiles * 255).clip(0, 255).astype(np.uint8), mode="RGB").convert(
"HSV"
),
dtype=np.float32,
)
h_ch, s_ch, v_ch = hsv[..., 0], hsv[..., 1], hsv[..., 2]
s_ch = np.clip(s_ch * sat_boost + sat_lift * 255.0, 0, 255)
hsv_boost = np.stack([h_ch, s_ch, v_ch], axis=-1).astype(np.uint8)
out = np.asarray(Image.fromarray(hsv_boost, mode="HSV").convert("RGB"), dtype=np.float32)
return out / 255.0
def windows_from_image(y: np.ndarray) -> tuple[torch.Tensor, torch.Tensor, int, int]:
"""Pad 4px, extract every cell window. Returns [N,2,24,16], rows, cols."""
H, W = y.shape
assert H % CELL_H == 0 and W % CELL_W == 0
rows, cols = H // CELL_H, W // CELL_W
gray = np.pad(y, ((BORDER, BORDER), (BORDER, BORDER)), mode="constant")
mask = np.zeros_like(gray, dtype=np.float32)
mask[BORDER : BORDER + H, BORDER : BORDER + W] = 1.0
wins = []
for ry in range(rows):
for cx in range(cols):
y0 = ry * CELL_H
x0 = cx * CELL_W
g = gray[y0 : y0 + WIN_H, x0 : x0 + WIN_W]
m = mask[y0 : y0 + WIN_H, x0 : x0 + WIN_W]
wins.append(np.stack([g * m, m], axis=0))
x = torch.from_numpy(np.stack(wins, axis=0).astype(np.float32))
return x, rows, cols
@torch.no_grad()
def encode(
model: PatchToGlyph,
bank: GlyphBank,
y: np.ndarray,
device: torch.device,
batch: int = 2048,
) -> tuple[list[str], torch.Tensor]:
model.eval()
windows, rows, cols = windows_from_image(y)
logits_all = []
for i in range(0, windows.shape[0], batch):
chunk = windows[i : i + batch].to(device)
logits_all.append(model(chunk).float().cpu())
logits = torch.cat(logits_all, dim=0)
idx = logits.argmax(dim=-1)
chars = bank.decode_indices(idx)
lines = [
"".join(chars[r * cols : (r + 1) * cols]) for r in range(rows)
]
return lines, idx.view(rows, cols)
def render_ascii_png(
indices: torch.Tensor,
bank: GlyphBank,
out_path: Path,
scale: int = 1,
colors: np.ndarray | None = None,
) -> None:
"""Blit VGA bitmaps for each cell → greyscale or color PNG (light on dark).
If `colors` is provided as [rows, cols, 3] in [0,1], each glyph is tinted by
that cell's color: out = glyph * color.
"""
rows, cols = indices.shape
bitmaps = bank.bitmaps.cpu().numpy()
if colors is None:
canvas = np.zeros((rows * CELL_H, cols * CELL_W), dtype=np.float32)
for r in range(rows):
for c in range(cols):
g = bitmaps[int(indices[r, c])]
canvas[
r * CELL_H : (r + 1) * CELL_H,
c * CELL_W : (c + 1) * CELL_W,
] = g
img = Image.fromarray((canvas * 255).clip(0, 255).astype(np.uint8), mode="L")
else:
assert colors.shape[:2] == (rows, cols), colors.shape
canvas = np.zeros((rows * CELL_H, cols * CELL_W, 3), dtype=np.float32)
for r in range(rows):
for c in range(cols):
g = bitmaps[int(indices[r, c])]
canvas[
r * CELL_H : (r + 1) * CELL_H,
c * CELL_W : (c + 1) * CELL_W,
:,
] = g[..., None] * colors[r, c][None, None, :]
img = Image.fromarray((canvas * 255).clip(0, 255).astype(np.uint8), mode="RGB")
if scale > 1:
img = img.resize(
(img.width * scale, img.height * scale), Image.Resampling.NEAREST
)
out_path.parent.mkdir(parents=True, exist_ok=True)
img.save(out_path)
def parse_args():
p = argparse.ArgumentParser(description="asc-eye image → ASCII PNG")
p.add_argument("--image", type=str, required=True)
p.add_argument("--ckpt", type=str, required=True)
p.add_argument("--font", type=str, default="./assets/VGA8.F16")
p.add_argument("--charset", type=str, default="ascii", choices=("ascii", "cp437"))
p.add_argument("--width_cells", type=int, default=120)
p.add_argument("--out_txt", type=str, default="")
p.add_argument("--out_png", type=str, required=True)
p.add_argument("--scale", type=int, default=2, help="nearest-neighbor upscale for PNG")
p.add_argument("--color", action="store_true", help="tint glyphs by per-cell mean RGB")
p.add_argument("--device", type=str, default="cuda")
return p.parse_args()
def main():
args = parse_args()
device = torch.device(
args.device if args.device != "cuda" or torch.cuda.is_available() else "cpu"
)
bank = GlyphBank(args.font, charset=args.charset).to(device)
ckpt = torch.load(args.ckpt, map_location=device, weights_only=False)
meta = ckpt.get("meta") or {}
# Prefer checkpoint's recorded charset/K if present
ck_args = meta.get("args") or {}
charset = ck_args.get("charset", args.charset)
if charset != args.charset:
print(f"[encode] ckpt charset={charset} (overriding CLI {args.charset})")
bank = GlyphBank(args.font, charset=charset).to(device)
model = PatchToGlyph(bank.K).to(device)
model.load_state_dict(ckpt["model"])
step = ckpt.get("step", "?")
print(f"[encode] loaded step={step} K={bank.K} charset={bank.charset} device={device}")
img = Image.open(args.image)
if args.color:
y, rgb = prepare_luma_rgb(img, args.width_cells)
colors = cell_mean_colors(rgb)
else:
y = prepare_luma(Path(args.image), args.width_cells)
colors = None
print(f"[encode] luma grid {y.shape[1]//CELL_W}×{y.shape[0]//CELL_H} cells ({y.shape[1]}×{y.shape[0]} px)")
lines, indices = encode(model, bank, y, device)
txt = "\n".join(lines) + "\n"
out_txt = Path(args.out_txt) if args.out_txt else Path(args.out_png).with_suffix(".txt")
out_txt.write_text(txt, encoding="utf-8")
render_ascii_png(indices, bank, Path(args.out_png), scale=args.scale, colors=colors)
print(f"[encode] wrote {out_txt} ({len(lines)} lines)")
print(f"[encode] wrote {args.out_png}")
if __name__ == "__main__":
main()