Revert to v2.3 version
Browse files- PBC2_4.py +0 -818
- PBC2_4_stream_patch.py +0 -286
- server.py +57 -128
- static/app.js +5 -10
- static/index.html +1 -1
- static/styles.css +1 -1
PBC2_4.py
DELETED
|
@@ -1,818 +0,0 @@
|
|
| 1 |
-
"""PBC2.4 clean core codec.
|
| 2 |
-
|
| 3 |
-
Self-contained refactor of the PBC2.x codec line. It keeps the classic random-stroke
|
| 4 |
-
algorithm, adds the PBC3.4 hybrid focus optimization, and drops demo/comparison code.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
from __future__ import annotations
|
| 8 |
-
|
| 9 |
-
from dataclasses import dataclass, replace
|
| 10 |
-
from time import perf_counter
|
| 11 |
-
from typing import Optional, Union
|
| 12 |
-
|
| 13 |
-
import numpy as np
|
| 14 |
-
from numba import njit, uint32, uint64
|
| 15 |
-
from PIL import Image
|
| 16 |
-
|
| 17 |
-
MAGIC = b"PBC24"
|
| 18 |
-
VERSION = 1
|
| 19 |
-
|
| 20 |
-
RESAMPLE = {
|
| 21 |
-
"nearest": Image.Resampling.NEAREST,
|
| 22 |
-
"box": Image.Resampling.BOX,
|
| 23 |
-
"bilinear": Image.Resampling.BILINEAR,
|
| 24 |
-
"hamming": Image.Resampling.HAMMING,
|
| 25 |
-
"bicubic": Image.Resampling.BICUBIC,
|
| 26 |
-
"lanczos": Image.Resampling.LANCZOS,
|
| 27 |
-
}
|
| 28 |
-
PLACEMENT = {"random": 0, "grid": 1, "hybrid": 2}
|
| 29 |
-
COLOR = {"RGB": 0, "YCbCr": 1}
|
| 30 |
-
CYCLE = {None: 0, False: 0, "Default": 1, "Strict": 2, "Balanced": 3, "Smart": 4}
|
| 31 |
-
CRITERIA = {"Sum": 0, "Max": 1, "Min": 2}
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
@dataclass
|
| 35 |
-
class PBCConfig:
|
| 36 |
-
stroke_count: int = -1
|
| 37 |
-
size_range: tuple[float, float] = (-1.0, -1.0)
|
| 38 |
-
mult_list: tuple[int, ...] = (-10, 0, 5, 20)
|
| 39 |
-
start_mode: str = "Average"
|
| 40 |
-
start_custom: tuple[int, int, int] = (128, 128, 128)
|
| 41 |
-
decay_cutoff: float = -1.0
|
| 42 |
-
decay_softness: float = -1.0
|
| 43 |
-
decay_progress: float = -1.0
|
| 44 |
-
focus_strokes: int = 100
|
| 45 |
-
focus_warmup: float = -1.0
|
| 46 |
-
focus_max_bits: int = 8
|
| 47 |
-
focus_padding: int = 4
|
| 48 |
-
focus_criteria: str = "Sum"
|
| 49 |
-
focus_mode: str = "auto"
|
| 50 |
-
focus_sample_side: int = 384
|
| 51 |
-
focus_sample_threshold: int = 1536
|
| 52 |
-
channel_cycle: Union[str, bool, None] = "Smart"
|
| 53 |
-
channel_cycle_strokes: int = 100
|
| 54 |
-
channel_cycle_warmup: float = 0.9
|
| 55 |
-
channel_cycle_criteria: str = "Min"
|
| 56 |
-
color_space: str = "RGB"
|
| 57 |
-
downsample_rate: float = -1.0
|
| 58 |
-
downsample_initialize: bool = True
|
| 59 |
-
downsample_initialize_rate: float = 16.0
|
| 60 |
-
downsample_initialize_bits: int = 8
|
| 61 |
-
resample: str = "bicubic"
|
| 62 |
-
placement_mode: str = "random"
|
| 63 |
-
seed: int = 2003
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
@dataclass
|
| 67 |
-
class PBCResult:
|
| 68 |
-
image: Image.Image
|
| 69 |
-
data: bytes
|
| 70 |
-
config: PBCConfig
|
| 71 |
-
losses: tuple[int, int, int]
|
| 72 |
-
mse: int
|
| 73 |
-
header_bits: int
|
| 74 |
-
total_bits: int
|
| 75 |
-
encode_seconds: float
|
| 76 |
-
|
| 77 |
-
def save(self, path: str) -> None:
|
| 78 |
-
with open(path, "wb") as f:
|
| 79 |
-
f.write(self.data)
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
class BitWriter:
|
| 83 |
-
def __init__(self):
|
| 84 |
-
self.buf = bytearray()
|
| 85 |
-
self.acc = 0
|
| 86 |
-
self.n = 0
|
| 87 |
-
self.bits = 0
|
| 88 |
-
|
| 89 |
-
def write(self, value: int, count: int) -> None:
|
| 90 |
-
value = int(value)
|
| 91 |
-
for i in range(count - 1, -1, -1):
|
| 92 |
-
self.acc = (self.acc << 1) | ((value >> i) & 1)
|
| 93 |
-
self.n += 1
|
| 94 |
-
self.bits += 1
|
| 95 |
-
if self.n == 8:
|
| 96 |
-
self.buf.append(self.acc)
|
| 97 |
-
self.acc = 0
|
| 98 |
-
self.n = 0
|
| 99 |
-
|
| 100 |
-
def write_signed(self, value: int, count: int) -> None:
|
| 101 |
-
self.write(0 if value < 0 else 1, 1)
|
| 102 |
-
self.write(abs(int(value)), count - 1)
|
| 103 |
-
|
| 104 |
-
def write_float(self, value: float, decimals: int = 4, count: int = 20) -> None:
|
| 105 |
-
self.write(int(round(value * (10 ** decimals))), count)
|
| 106 |
-
|
| 107 |
-
def write_array(self, arr: np.ndarray, bits: int) -> None:
|
| 108 |
-
for v in arr.reshape(-1):
|
| 109 |
-
self.write(int(v), bits)
|
| 110 |
-
|
| 111 |
-
def finish(self) -> tuple[bytes, int]:
|
| 112 |
-
pad = (8 - self.n) % 8
|
| 113 |
-
if self.n:
|
| 114 |
-
self.buf.append(self.acc << pad)
|
| 115 |
-
return bytes(self.buf), pad
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
class BitReader:
|
| 119 |
-
def __init__(self, data: bytes):
|
| 120 |
-
self.data = data
|
| 121 |
-
self.i = 0
|
| 122 |
-
self.bits = 0
|
| 123 |
-
|
| 124 |
-
def read(self, count: int) -> int:
|
| 125 |
-
v = 0
|
| 126 |
-
for _ in range(count):
|
| 127 |
-
byte = self.data[self.i >> 3]
|
| 128 |
-
bit = (byte >> (7 - (self.i & 7))) & 1
|
| 129 |
-
v = (v << 1) | bit
|
| 130 |
-
self.i += 1
|
| 131 |
-
self.bits += 1
|
| 132 |
-
return v
|
| 133 |
-
|
| 134 |
-
def read_signed(self, count: int) -> int:
|
| 135 |
-
sign = self.read(1)
|
| 136 |
-
v = self.read(count - 1)
|
| 137 |
-
return v if sign else -v
|
| 138 |
-
|
| 139 |
-
def read_float(self, decimals: int = 4, count: int = 20) -> float:
|
| 140 |
-
return self.read(count) / (10 ** decimals)
|
| 141 |
-
|
| 142 |
-
def read_array(self, shape: tuple[int, ...], bits: int) -> np.ndarray:
|
| 143 |
-
arr = np.empty(int(np.prod(shape)), dtype=np.uint8)
|
| 144 |
-
for i in range(arr.size):
|
| 145 |
-
arr[i] = self.read(bits)
|
| 146 |
-
return arr.reshape(shape)
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
@njit(inline="always")
|
| 150 |
-
def _pcg_step(state):
|
| 151 |
-
old = state
|
| 152 |
-
state = uint64(old * 6364136223846793005 + 1442695040888963407)
|
| 153 |
-
x = uint32(((old >> 18) ^ old) >> 27)
|
| 154 |
-
rot = uint32(old >> 59)
|
| 155 |
-
out = (x >> rot) | (x << ((-rot) & 31))
|
| 156 |
-
return state, out
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
@njit(inline="always")
|
| 160 |
-
def _focus_bitcount(h, w, size, max_bits):
|
| 161 |
-
ch, cw = h, w
|
| 162 |
-
bits = 0
|
| 163 |
-
split_h = True
|
| 164 |
-
while bits < max_bits:
|
| 165 |
-
if split_h:
|
| 166 |
-
if ch // 2 < size:
|
| 167 |
-
break
|
| 168 |
-
ch //= 2
|
| 169 |
-
else:
|
| 170 |
-
if cw // 2 < size:
|
| 171 |
-
break
|
| 172 |
-
cw //= 2
|
| 173 |
-
split_h = not split_h
|
| 174 |
-
bits += 1
|
| 175 |
-
return bits
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
@njit(inline="always")
|
| 179 |
-
def _focus_bounds(h, w, size, code, bits, pad):
|
| 180 |
-
rs, re, cs, ce = 0, h, 0, w
|
| 181 |
-
split_h = True
|
| 182 |
-
for b in range(bits - 1, -1, -1):
|
| 183 |
-
bit = (code >> b) & 1
|
| 184 |
-
if split_h:
|
| 185 |
-
mid = (rs + re) // 2
|
| 186 |
-
if bit == 0:
|
| 187 |
-
re = mid
|
| 188 |
-
else:
|
| 189 |
-
rs = mid
|
| 190 |
-
else:
|
| 191 |
-
mid = (cs + ce) // 2
|
| 192 |
-
if bit == 0:
|
| 193 |
-
ce = mid
|
| 194 |
-
else:
|
| 195 |
-
cs = mid
|
| 196 |
-
split_h = not split_h
|
| 197 |
-
re -= size
|
| 198 |
-
ce -= size
|
| 199 |
-
rs = max(0, rs - pad)
|
| 200 |
-
cs = max(0, cs - pad)
|
| 201 |
-
re = min(h - size, re + pad)
|
| 202 |
-
ce = min(w - size, ce + pad)
|
| 203 |
-
if re <= rs:
|
| 204 |
-
re = rs + 1
|
| 205 |
-
if ce <= cs:
|
| 206 |
-
ce = cs + 1
|
| 207 |
-
return rs, cs, re, ce
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
@njit
|
| 211 |
-
def _select_focus_exact(target, canvas, h, w, bits, criteria):
|
| 212 |
-
if bits == 0:
|
| 213 |
-
return 0
|
| 214 |
-
best_code = 0
|
| 215 |
-
best = -1.0
|
| 216 |
-
for code in range(1 << bits):
|
| 217 |
-
rs, cs, re, ce = _focus_bounds(h, w, 0, code, bits, 0)
|
| 218 |
-
if criteria == 0:
|
| 219 |
-
val = 0.0
|
| 220 |
-
for r in range(rs, re):
|
| 221 |
-
for c in range(cs, ce):
|
| 222 |
-
d = target[r, c] - canvas[r, c]
|
| 223 |
-
val += abs(d)
|
| 224 |
-
elif criteria == 1:
|
| 225 |
-
val = 0.0
|
| 226 |
-
for r in range(rs, re):
|
| 227 |
-
for c in range(cs, ce):
|
| 228 |
-
d = abs(target[r, c] - canvas[r, c])
|
| 229 |
-
if d > val:
|
| 230 |
-
val = d
|
| 231 |
-
else:
|
| 232 |
-
val = 1e18
|
| 233 |
-
for r in range(rs, re):
|
| 234 |
-
for c in range(cs, ce):
|
| 235 |
-
d = abs(target[r, c] - canvas[r, c])
|
| 236 |
-
if d < val:
|
| 237 |
-
val = d
|
| 238 |
-
if val > best:
|
| 239 |
-
best = val
|
| 240 |
-
best_code = code
|
| 241 |
-
return best_code
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
@njit(inline="always")
|
| 245 |
-
def _sample_focus_code(r, c, h, w, bits):
|
| 246 |
-
rs, re, cs, ce = 0, h, 0, w
|
| 247 |
-
code = 0
|
| 248 |
-
split_h = True
|
| 249 |
-
for _ in range(bits):
|
| 250 |
-
code <<= 1
|
| 251 |
-
if split_h:
|
| 252 |
-
mid = (rs + re) // 2
|
| 253 |
-
if r >= mid:
|
| 254 |
-
code |= 1
|
| 255 |
-
rs = mid
|
| 256 |
-
else:
|
| 257 |
-
re = mid
|
| 258 |
-
else:
|
| 259 |
-
mid = (cs + ce) // 2
|
| 260 |
-
if c >= mid:
|
| 261 |
-
code |= 1
|
| 262 |
-
cs = mid
|
| 263 |
-
else:
|
| 264 |
-
ce = mid
|
| 265 |
-
split_h = not split_h
|
| 266 |
-
return code
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
@njit
|
| 270 |
-
def _select_focus_sampled(target, canvas, h, w, bits, sample_side):
|
| 271 |
-
if bits == 0:
|
| 272 |
-
return 0
|
| 273 |
-
sums = np.zeros(1 << bits, dtype=np.float64)
|
| 274 |
-
sr = min(h, sample_side)
|
| 275 |
-
sc = min(w, sample_side)
|
| 276 |
-
for ir in range(sr):
|
| 277 |
-
r = (ir * h + h // 2) // sr
|
| 278 |
-
if r >= h:
|
| 279 |
-
r = h - 1
|
| 280 |
-
for ic in range(sc):
|
| 281 |
-
c = (ic * w + w // 2) // sc
|
| 282 |
-
if c >= w:
|
| 283 |
-
c = w - 1
|
| 284 |
-
d = target[r, c] - canvas[r, c]
|
| 285 |
-
if d < 0:
|
| 286 |
-
d = -d
|
| 287 |
-
sums[_sample_focus_code(r, c, h, w, bits)] += d
|
| 288 |
-
best_code = 0
|
| 289 |
-
best = sums[0]
|
| 290 |
-
for i in range(1, sums.size):
|
| 291 |
-
if sums[i] > best:
|
| 292 |
-
best = sums[i]
|
| 293 |
-
best_code = i
|
| 294 |
-
return best_code
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
@njit(inline="always")
|
| 298 |
-
def _coords(state, i, mode, rs, cs, re, ce, size):
|
| 299 |
-
if re <= rs:
|
| 300 |
-
re = rs + 1
|
| 301 |
-
if ce <= cs:
|
| 302 |
-
ce = cs + 1
|
| 303 |
-
if mode == 0 or (mode == 2 and (i & 1) == 1):
|
| 304 |
-
state, rr = _pcg_step(state)
|
| 305 |
-
state, cc = _pcg_step(state)
|
| 306 |
-
return state, rs + int(rr % uint32(re - rs)), cs + int(cc % uint32(ce - cs))
|
| 307 |
-
gh = max(1, (re - rs) // max(1, size))
|
| 308 |
-
gw = max(1, (ce - cs) // max(1, size))
|
| 309 |
-
idx = i % (gh * gw)
|
| 310 |
-
gr = idx // gw
|
| 311 |
-
gc = idx % gw
|
| 312 |
-
row = rs if gh == 1 else rs + (gr * (re - rs - 1)) // (gh - 1)
|
| 313 |
-
col = cs if gw == 1 else cs + (gc * (ce - cs - 1)) // (gw - 1)
|
| 314 |
-
return state, row, col
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
@njit(inline="always")
|
| 318 |
-
def _apply_tile(target, canvas, r0, r1, c0, c1, mults):
|
| 319 |
-
if r0 >= r1 or c0 >= c1:
|
| 320 |
-
return 0
|
| 321 |
-
s = 0.0
|
| 322 |
-
n = 0
|
| 323 |
-
for r in range(r0, r1):
|
| 324 |
-
for c in range(c0, c1):
|
| 325 |
-
s += target[r, c] - canvas[r, c]
|
| 326 |
-
n += 1
|
| 327 |
-
mean = s / n
|
| 328 |
-
best_i = 0
|
| 329 |
-
best_d = abs(mults[0] - mean)
|
| 330 |
-
for i in range(1, mults.size):
|
| 331 |
-
d = abs(mults[i] - mean)
|
| 332 |
-
if d < best_d:
|
| 333 |
-
best_d = d
|
| 334 |
-
best_i = i
|
| 335 |
-
m = mults[best_i]
|
| 336 |
-
if m != 0:
|
| 337 |
-
for r in range(r0, r1):
|
| 338 |
-
for c in range(c0, c1):
|
| 339 |
-
v = canvas[r, c] + m
|
| 340 |
-
if v < 0:
|
| 341 |
-
v = 0
|
| 342 |
-
elif v > 255:
|
| 343 |
-
v = 255
|
| 344 |
-
canvas[r, c] = v
|
| 345 |
-
return best_i
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
@njit
|
| 349 |
-
def _channel_selector(target, canvas, strategy, criteria):
|
| 350 |
-
out = np.empty(3, dtype=np.int64)
|
| 351 |
-
out[0], out[1], out[2] = 0, 1, 2
|
| 352 |
-
if strategy == 1:
|
| 353 |
-
return out
|
| 354 |
-
errs = np.zeros(3, dtype=np.float64)
|
| 355 |
-
h, w = target.shape[0], target.shape[1]
|
| 356 |
-
for ch in range(3):
|
| 357 |
-
if criteria == 0:
|
| 358 |
-
s = 0.0
|
| 359 |
-
for r in range(h):
|
| 360 |
-
for c in range(w):
|
| 361 |
-
s += abs(target[r, c, ch] - canvas[r, c, ch])
|
| 362 |
-
errs[ch] = s
|
| 363 |
-
elif criteria == 1:
|
| 364 |
-
m = 0.0
|
| 365 |
-
for r in range(h):
|
| 366 |
-
for c in range(w):
|
| 367 |
-
d = abs(target[r, c, ch] - canvas[r, c, ch])
|
| 368 |
-
if d > m:
|
| 369 |
-
m = d
|
| 370 |
-
errs[ch] = m
|
| 371 |
-
else:
|
| 372 |
-
m = 1e18
|
| 373 |
-
for r in range(h):
|
| 374 |
-
for c in range(w):
|
| 375 |
-
d = abs(target[r, c, ch] - canvas[r, c, ch])
|
| 376 |
-
if d < m:
|
| 377 |
-
m = d
|
| 378 |
-
errs[ch] = m
|
| 379 |
-
order = np.argsort(errs)[::-1]
|
| 380 |
-
if strategy == 2:
|
| 381 |
-
out[:] = order[0]
|
| 382 |
-
elif strategy == 3:
|
| 383 |
-
out[0], out[1], out[2] = order[0], order[0], order[1]
|
| 384 |
-
elif strategy == 4:
|
| 385 |
-
if errs[order[0]] > 2 * errs[order[1]]:
|
| 386 |
-
out[:] = order[0]
|
| 387 |
-
elif errs[order[1]] > 2 * errs[order[2]]:
|
| 388 |
-
out[0], out[1], out[2] = order[0], order[0], order[1]
|
| 389 |
-
return out
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
@njit
|
| 393 |
-
def _encode_loop(target, canvas, sizes, mults, seed, placement, focus_strokes, focus_warmup, focus_max_bits, focus_pad, focus_criteria, focus_mode, sample_side, cycle_mode, cycle_strokes, cycle_warmup, cycle_criteria):
|
| 394 |
-
n = sizes.size
|
| 395 |
-
h, w = target.shape[0], target.shape[1]
|
| 396 |
-
indices = np.zeros((n, 4), dtype=np.uint16)
|
| 397 |
-
focus_codes = np.full(n, -1, dtype=np.int64)
|
| 398 |
-
focus_bits = np.zeros(n, dtype=np.uint8)
|
| 399 |
-
cycle_codes = np.full((n, 3), -1, dtype=np.int64)
|
| 400 |
-
counters = np.empty(3, dtype=np.int64)
|
| 401 |
-
counters[0] = counters[1] = counters[2] = focus_warmup // 3
|
| 402 |
-
fcodes = np.zeros(3, dtype=np.int64)
|
| 403 |
-
fbits = np.zeros(3, dtype=np.int64)
|
| 404 |
-
selector = np.empty(3, dtype=np.int64)
|
| 405 |
-
selector[0], selector[1], selector[2] = 0, 1, 2
|
| 406 |
-
timer = cycle_warmup
|
| 407 |
-
state = uint64(seed)
|
| 408 |
-
for i in range(n):
|
| 409 |
-
size = sizes[i]
|
| 410 |
-
channel = selector[i % 3]
|
| 411 |
-
if counters[channel] <= 0:
|
| 412 |
-
bits = _focus_bitcount(h, w, size, focus_max_bits)
|
| 413 |
-
if focus_mode == 2:
|
| 414 |
-
code = _select_focus_sampled(target[:, :, channel], canvas[:, :, channel], h, w, bits, sample_side)
|
| 415 |
-
else:
|
| 416 |
-
code = _select_focus_exact(target[:, :, channel], canvas[:, :, channel], h, w, bits, focus_criteria)
|
| 417 |
-
fcodes[channel] = code
|
| 418 |
-
fbits[channel] = bits
|
| 419 |
-
focus_codes[i] = code
|
| 420 |
-
focus_bits[i] = bits
|
| 421 |
-
counters[channel] = focus_strokes
|
| 422 |
-
if cycle_mode != 0 and timer <= 0:
|
| 423 |
-
selector = _channel_selector(target, canvas, cycle_mode, cycle_criteria)
|
| 424 |
-
cycle_codes[i, 0], cycle_codes[i, 1], cycle_codes[i, 2] = selector[0], selector[1], selector[2]
|
| 425 |
-
timer = cycle_strokes
|
| 426 |
-
if fbits[channel] > 0:
|
| 427 |
-
rs, cs, re, ce = _focus_bounds(h, w, size, fcodes[channel], fbits[channel], focus_pad)
|
| 428 |
-
else:
|
| 429 |
-
rs, cs, re, ce = 0, 0, h - size, w - size
|
| 430 |
-
state, row, col = _coords(state, i, placement, rs, cs, re, ce, size)
|
| 431 |
-
half = size // 2
|
| 432 |
-
indices[i, 0] = _apply_tile(target[:, :, channel], canvas[:, :, channel], row, row + half, col, col + half, mults)
|
| 433 |
-
indices[i, 1] = _apply_tile(target[:, :, channel], canvas[:, :, channel], row, row + half, col + half, col + size, mults)
|
| 434 |
-
indices[i, 2] = _apply_tile(target[:, :, channel], canvas[:, :, channel], row + half, row + size, col, col + half, mults)
|
| 435 |
-
indices[i, 3] = _apply_tile(target[:, :, channel], canvas[:, :, channel], row + half, row + size, col + half, col + size, mults)
|
| 436 |
-
counters[channel] -= 1
|
| 437 |
-
if cycle_mode != 0:
|
| 438 |
-
timer -= 1
|
| 439 |
-
return indices, focus_codes, focus_bits, cycle_codes, canvas
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
@njit
|
| 443 |
-
def _decode_loop(canvas, sizes, mults, indices, focus_codes, focus_bits, cycle_codes, seed, placement, focus_strokes, focus_warmup, focus_pad, cycle_mode, cycle_strokes, cycle_warmup):
|
| 444 |
-
n = sizes.size
|
| 445 |
-
h, w = canvas.shape[0], canvas.shape[1]
|
| 446 |
-
counters = np.empty(3, dtype=np.int64)
|
| 447 |
-
counters[0] = counters[1] = counters[2] = focus_warmup // 3
|
| 448 |
-
fcodes = np.zeros(3, dtype=np.int64)
|
| 449 |
-
fbits = np.zeros(3, dtype=np.int64)
|
| 450 |
-
selector = np.empty(3, dtype=np.int64)
|
| 451 |
-
selector[0], selector[1], selector[2] = 0, 1, 2
|
| 452 |
-
timer = cycle_warmup
|
| 453 |
-
state = uint64(seed)
|
| 454 |
-
for i in range(n):
|
| 455 |
-
size = sizes[i]
|
| 456 |
-
channel = selector[i % 3]
|
| 457 |
-
if focus_codes[i] >= 0:
|
| 458 |
-
fcodes[channel] = focus_codes[i]
|
| 459 |
-
fbits[channel] = focus_bits[i]
|
| 460 |
-
counters[channel] = focus_strokes
|
| 461 |
-
if cycle_mode != 0 and cycle_codes[i, 0] >= 0:
|
| 462 |
-
selector[0], selector[1], selector[2] = cycle_codes[i, 0], cycle_codes[i, 1], cycle_codes[i, 2]
|
| 463 |
-
timer = cycle_strokes
|
| 464 |
-
if fbits[channel] > 0:
|
| 465 |
-
rs, cs, re, ce = _focus_bounds(h, w, size, fcodes[channel], fbits[channel], focus_pad)
|
| 466 |
-
else:
|
| 467 |
-
rs, cs, re, ce = 0, 0, h - size, w - size
|
| 468 |
-
state, row, col = _coords(state, i, placement, rs, cs, re, ce, size)
|
| 469 |
-
half = size // 2
|
| 470 |
-
for k in range(4):
|
| 471 |
-
if k == 0:
|
| 472 |
-
r0, r1, c0, c1 = row, row + half, col, col + half
|
| 473 |
-
elif k == 1:
|
| 474 |
-
r0, r1, c0, c1 = row, row + half, col + half, col + size
|
| 475 |
-
elif k == 2:
|
| 476 |
-
r0, r1, c0, c1 = row + half, row + size, col, col + half
|
| 477 |
-
else:
|
| 478 |
-
r0, r1, c0, c1 = row + half, row + size, col + half, col + size
|
| 479 |
-
m = mults[indices[i, k]]
|
| 480 |
-
if m != 0:
|
| 481 |
-
for r in range(r0, r1):
|
| 482 |
-
for c in range(c0, c1):
|
| 483 |
-
v = canvas[r, c, channel] + m
|
| 484 |
-
if v < 0:
|
| 485 |
-
v = 0
|
| 486 |
-
elif v > 255:
|
| 487 |
-
v = 255
|
| 488 |
-
canvas[r, c, channel] = v
|
| 489 |
-
counters[channel] -= 1
|
| 490 |
-
if cycle_mode != 0:
|
| 491 |
-
timer -= 1
|
| 492 |
-
return canvas
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
def _resample_id(name: str) -> int:
|
| 496 |
-
return list(RESAMPLE).index(name)
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
def _resample_name(idx: int) -> str:
|
| 500 |
-
return list(RESAMPLE)[idx]
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
def _decay(length: int, start: int, end: int, cutoff: float, softness: float, progress: float):
|
| 504 |
-
if cutoff == -1:
|
| 505 |
-
cutoff = 0.01 + (1 / 1.0000115) ** (length + 15000)
|
| 506 |
-
if softness == -1:
|
| 507 |
-
softness = 0.5
|
| 508 |
-
if progress == -1:
|
| 509 |
-
progress = 0.5
|
| 510 |
-
cutoff, softness, progress = round(cutoff, 4), round(softness, 4), round(progress, 4)
|
| 511 |
-
x = np.linspace(0, length, length)
|
| 512 |
-
if cutoff <= 0:
|
| 513 |
-
return np.full(length, end, dtype=np.int64), cutoff, softness, progress
|
| 514 |
-
lencut = length * cutoff
|
| 515 |
-
if lencut >= length * 3:
|
| 516 |
-
return np.full(length, start, dtype=np.int64), cutoff, softness, progress
|
| 517 |
-
lin = start + (x / (length * cutoff)) * (end - start)
|
| 518 |
-
if softness <= 0:
|
| 519 |
-
sig = np.where(x >= lencut / 2, end, start)
|
| 520 |
-
else:
|
| 521 |
-
k = 1.0 / softness * (np.sqrt(abs(end - start)) / length)
|
| 522 |
-
sig = start + (end - start) / (1 + np.exp(-k * (x - lencut / 2)))
|
| 523 |
-
curve = progress * sig + (1 - progress) * lin
|
| 524 |
-
curve[x >= lencut] = end
|
| 525 |
-
return (curve // 2 * 2).astype(np.int64), cutoff, softness, progress
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
def _rgb_to_ycbcr(img):
|
| 529 |
-
return np.asarray(Image.fromarray(np.clip(img, 0, 255).astype(np.uint8), "RGB").convert("YCbCr"), dtype=np.int16)
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
def _ycbcr_to_rgb(img):
|
| 533 |
-
return np.asarray(Image.fromarray(np.clip(img, 0, 255).astype(np.uint8), "YCbCr").convert("RGB"), dtype=np.uint8)
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
def _prepare_config(img_size, cfg: PBCConfig) -> PBCConfig:
|
| 537 |
-
cfg = replace(cfg)
|
| 538 |
-
if cfg.stroke_count == -1:
|
| 539 |
-
cfg.stroke_count = int(20000 + 0.0015 * ((max(img_size) + 3200) ** 2))
|
| 540 |
-
if cfg.downsample_rate == -1:
|
| 541 |
-
cfg.downsample_rate = 1 if min(img_size) < 600 else min(img_size) / 500
|
| 542 |
-
if cfg.downsample_initialize and cfg.downsample_initialize_rate < 32:
|
| 543 |
-
if cfg.stroke_count > 20000:
|
| 544 |
-
if cfg.decay_cutoff == -1:
|
| 545 |
-
cfg.decay_cutoff = 0.3
|
| 546 |
-
if cfg.size_range == (-1.0, -1.0):
|
| 547 |
-
cfg.size_range = (0.05, 0.01)
|
| 548 |
-
if cfg.focus_warmup == -1:
|
| 549 |
-
cfg.focus_warmup = 0.1
|
| 550 |
-
else:
|
| 551 |
-
if cfg.decay_cutoff == -1:
|
| 552 |
-
cfg.decay_cutoff = 0.7
|
| 553 |
-
if cfg.size_range == (-1.0, -1.0):
|
| 554 |
-
cfg.size_range = (0.1, 0.03)
|
| 555 |
-
if cfg.focus_warmup == -1:
|
| 556 |
-
cfg.focus_warmup = 0.7
|
| 557 |
-
if cfg.focus_warmup == -1:
|
| 558 |
-
v = 0.75 - (0.000014 * (cfg.stroke_count - 1000) ** 2) / 550000
|
| 559 |
-
cfg.focus_warmup = max(0.0, min(v, 1.0))
|
| 560 |
-
return cfg
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
def _start_color(img, cfg: PBCConfig):
|
| 564 |
-
if cfg.start_mode == "Black":
|
| 565 |
-
return (0, 0, 0) if cfg.color_space == "RGB" else (0, 128, 128)
|
| 566 |
-
if cfg.start_mode == "White":
|
| 567 |
-
return (255, 255, 255) if cfg.color_space == "RGB" else (255, 128, 128)
|
| 568 |
-
if cfg.start_mode == "Custom":
|
| 569 |
-
return cfg.start_custom
|
| 570 |
-
if cfg.start_mode == "Median":
|
| 571 |
-
return tuple(int(np.median(img[:, :, c])) for c in range(3))
|
| 572 |
-
if cfg.start_mode == "True Median":
|
| 573 |
-
return tuple(np.median(img.reshape(-1, 3), axis=0).astype(int))
|
| 574 |
-
return tuple(int(np.mean(img[:, :, c])) for c in range(3))
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
def _pack(cfg, w, h, original_size, sizes, decay_vals, start_color, init, symbols):
|
| 578 |
-
writer = BitWriter()
|
| 579 |
-
writer.write(1 if cfg.downsample_rate > 1 else 0, 1)
|
| 580 |
-
if cfg.downsample_rate > 1:
|
| 581 |
-
writer.write(original_size[0], 16)
|
| 582 |
-
writer.write(original_size[1], 16)
|
| 583 |
-
writer.write(1 if cfg.color_space == "YCbCr" else 0, 1)
|
| 584 |
-
writer.write(_resample_id(cfg.resample), 3)
|
| 585 |
-
writer.write(h, 16)
|
| 586 |
-
writer.write(w, 16)
|
| 587 |
-
writer.write(cfg.stroke_count, 32)
|
| 588 |
-
for v in start_color:
|
| 589 |
-
writer.write(v, 8)
|
| 590 |
-
writer.write(1 if cfg.downsample_initialize else 0, 1)
|
| 591 |
-
if cfg.downsample_initialize:
|
| 592 |
-
writer.write(init.shape[0], 16)
|
| 593 |
-
writer.write(init.shape[1], 16)
|
| 594 |
-
writer.write(cfg.downsample_initialize_bits, 4)
|
| 595 |
-
writer.write_array(init, cfg.downsample_initialize_bits)
|
| 596 |
-
writer.write(int(sizes[0]), 16)
|
| 597 |
-
writer.write(int(sizes[-1]), 16)
|
| 598 |
-
for flag, val in decay_vals:
|
| 599 |
-
writer.write(flag, 1)
|
| 600 |
-
writer.write_float(val)
|
| 601 |
-
writer.write(len(cfg.mult_list), 9)
|
| 602 |
-
for m in cfg.mult_list:
|
| 603 |
-
writer.write_signed(m, 9)
|
| 604 |
-
writer.write(int(cfg.focus_warmup * cfg.stroke_count), 32)
|
| 605 |
-
writer.write(cfg.focus_strokes, 20)
|
| 606 |
-
writer.write(cfg.focus_max_bits, 8)
|
| 607 |
-
writer.write(cfg.focus_padding, 8)
|
| 608 |
-
writer.write(CRITERIA[cfg.focus_criteria], 2)
|
| 609 |
-
writer.write(CYCLE[cfg.channel_cycle], 3)
|
| 610 |
-
if CYCLE[cfg.channel_cycle] != 0:
|
| 611 |
-
writer.write(cfg.channel_cycle_strokes, 20)
|
| 612 |
-
writer.write(int(cfg.channel_cycle_warmup * cfg.stroke_count), 32)
|
| 613 |
-
writer.write(CRITERIA[cfg.channel_cycle_criteria], 2)
|
| 614 |
-
writer.write(PLACEMENT[cfg.placement_mode], 2)
|
| 615 |
-
writer.write(cfg.seed, 64)
|
| 616 |
-
header_bits = writer.bits
|
| 617 |
-
|
| 618 |
-
indices, focus_codes, focus_bits, cycle_codes = symbols
|
| 619 |
-
mbits = int(np.ceil(np.log2(len(cfg.mult_list))))
|
| 620 |
-
for i in range(cfg.stroke_count):
|
| 621 |
-
if focus_codes[i] >= 0:
|
| 622 |
-
writer.write(int(focus_codes[i]), int(focus_bits[i]))
|
| 623 |
-
if cycle_codes[i, 0] >= 0:
|
| 624 |
-
writer.write(int(cycle_codes[i, 0]), 2)
|
| 625 |
-
writer.write(int(cycle_codes[i, 1]), 2)
|
| 626 |
-
writer.write(int(cycle_codes[i, 2]), 2)
|
| 627 |
-
for idx in indices[i]:
|
| 628 |
-
writer.write(int(idx), mbits)
|
| 629 |
-
|
| 630 |
-
payload, pad = writer.finish()
|
| 631 |
-
return MAGIC + bytes([VERSION, pad]) + payload, header_bits, writer.bits
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
class PBC:
|
| 635 |
-
Config = PBCConfig
|
| 636 |
-
Result = PBCResult
|
| 637 |
-
|
| 638 |
-
@staticmethod
|
| 639 |
-
def compress(img: Union[str, Image.Image, np.ndarray], config: Optional[PBCConfig] = None, **overrides) -> PBCResult:
|
| 640 |
-
t0 = perf_counter()
|
| 641 |
-
cfg = replace(config or PBCConfig(), **overrides)
|
| 642 |
-
pil = Image.open(img).convert("RGB") if isinstance(img, str) else Image.fromarray(img).convert("RGB") if isinstance(img, np.ndarray) else img.convert("RGB")
|
| 643 |
-
original_size = pil.size
|
| 644 |
-
cfg = _prepare_config(original_size, cfg)
|
| 645 |
-
resample = RESAMPLE[cfg.resample]
|
| 646 |
-
work_pil = pil
|
| 647 |
-
if cfg.downsample_rate > 1:
|
| 648 |
-
work_pil = pil.resize((max(1, int(pil.width / cfg.downsample_rate)), max(1, int(pil.height / cfg.downsample_rate))), resample)
|
| 649 |
-
target = np.asarray(work_pil, dtype=np.int16)
|
| 650 |
-
if cfg.color_space == "YCbCr":
|
| 651 |
-
target = _rgb_to_ycbcr(target)
|
| 652 |
-
h, w = target.shape[:2]
|
| 653 |
-
start = _start_color(target, cfg)
|
| 654 |
-
init = np.empty((0, 0, 3), dtype=np.uint8)
|
| 655 |
-
init_store = init
|
| 656 |
-
if cfg.downsample_initialize:
|
| 657 |
-
ih = max(1, int(h / cfg.downsample_initialize_rate))
|
| 658 |
-
iw = max(1, int(w / cfg.downsample_initialize_rate))
|
| 659 |
-
init = np.asarray(work_pil.resize((iw, ih), resample), dtype=np.uint8)
|
| 660 |
-
if cfg.downsample_initialize_bits < 8:
|
| 661 |
-
init = ((init >> (8 - cfg.downsample_initialize_bits)) << (8 - cfg.downsample_initialize_bits)).astype(np.uint8)
|
| 662 |
-
init_store = (init >> (8 - cfg.downsample_initialize_bits)).astype(np.uint8)
|
| 663 |
-
else:
|
| 664 |
-
init_store = init
|
| 665 |
-
canvas = np.asarray(Image.fromarray(init).resize((w, h), resample), dtype=np.int16)
|
| 666 |
-
if cfg.color_space == "YCbCr":
|
| 667 |
-
canvas = _rgb_to_ycbcr(canvas)
|
| 668 |
-
else:
|
| 669 |
-
canvas = np.full((h, w, 3), start, dtype=np.int16)
|
| 670 |
-
s0, s1 = cfg.size_range
|
| 671 |
-
if s0 == -1:
|
| 672 |
-
s0 = 0.3 + (1 / 1.00095) ** (cfg.stroke_count + 7000)
|
| 673 |
-
if s1 == -1:
|
| 674 |
-
s1 = 0.01 + (1 / 1.00015) ** (cfg.stroke_count + 10200)
|
| 675 |
-
sizes, cutoff, soft, prog = _decay(cfg.stroke_count, int(s0 * (min(h, w) - 2)) + 2, int(s1 * (min(h, w) - 2)) + 2, cfg.decay_cutoff, cfg.decay_softness, cfg.decay_progress)
|
| 676 |
-
if cfg.focus_mode == "sampled" or (cfg.focus_mode == "auto" and min(h, w) >= cfg.focus_sample_threshold):
|
| 677 |
-
focus_mode_id = 2
|
| 678 |
-
elif cfg.focus_mode in ("auto", "exact"):
|
| 679 |
-
focus_mode_id = 1
|
| 680 |
-
else:
|
| 681 |
-
raise ValueError("focus_mode must be 'auto', 'exact', or 'sampled'")
|
| 682 |
-
indices, focus_codes, focus_bits, cycle_codes, canvas = _encode_loop(
|
| 683 |
-
target, canvas, sizes, np.asarray(cfg.mult_list, dtype=np.int16), cfg.seed, PLACEMENT[cfg.placement_mode],
|
| 684 |
-
cfg.focus_strokes, int(cfg.focus_warmup * cfg.stroke_count), cfg.focus_max_bits, cfg.focus_padding,
|
| 685 |
-
CRITERIA[cfg.focus_criteria], focus_mode_id, cfg.focus_sample_side,
|
| 686 |
-
CYCLE[cfg.channel_cycle], cfg.channel_cycle_strokes, int(cfg.channel_cycle_warmup * cfg.stroke_count), CRITERIA[cfg.channel_cycle_criteria],
|
| 687 |
-
)
|
| 688 |
-
final = np.clip(canvas, 0, 255)
|
| 689 |
-
final = _ycbcr_to_rgb(final) if cfg.color_space == "YCbCr" else final.astype(np.uint8)
|
| 690 |
-
out_pil = Image.fromarray(final)
|
| 691 |
-
if cfg.downsample_rate > 1:
|
| 692 |
-
out_pil = out_pil.resize(original_size, resample)
|
| 693 |
-
data, header_bits, total_bits = _pack(cfg, w, h, original_size, sizes, ((cfg.decay_cutoff == -1, cutoff), (cfg.decay_softness == -1, soft), (cfg.decay_progress == -1, prog)), start, init_store, (indices, focus_codes, focus_bits, cycle_codes))
|
| 694 |
-
out = np.asarray(out_pil, dtype=np.uint8)
|
| 695 |
-
src = np.asarray(pil, dtype=np.uint8)
|
| 696 |
-
losses = tuple(int(np.mean((src[:, :, c].astype(np.float32) - out[:, :, c].astype(np.float32)) ** 2)) for c in range(3))
|
| 697 |
-
return PBCResult(out_pil, data, cfg, losses, int(sum(losses) / 3), header_bits, total_bits, perf_counter() - t0)
|
| 698 |
-
|
| 699 |
-
@staticmethod
|
| 700 |
-
def decompress(data: Union[bytes, bytearray, str], return_result: bool = False):
|
| 701 |
-
if isinstance(data, str):
|
| 702 |
-
with open(data, "rb") as f:
|
| 703 |
-
data = f.read()
|
| 704 |
-
if data[:5] != MAGIC or data[5] != VERSION:
|
| 705 |
-
raise ValueError("Not a PBC2.4 v1 stream")
|
| 706 |
-
reader = BitReader(bytes(data[7:]))
|
| 707 |
-
down = reader.read(1)
|
| 708 |
-
original_size = None
|
| 709 |
-
if down:
|
| 710 |
-
original_size = (reader.read(16), reader.read(16))
|
| 711 |
-
color_space = "YCbCr" if reader.read(1) else "RGB"
|
| 712 |
-
resample_name = _resample_name(reader.read(3))
|
| 713 |
-
resample = RESAMPLE[resample_name]
|
| 714 |
-
h, w = reader.read(16), reader.read(16)
|
| 715 |
-
stroke_count = reader.read(32)
|
| 716 |
-
start = tuple(reader.read(8) for _ in range(3))
|
| 717 |
-
down_init = bool(reader.read(1))
|
| 718 |
-
init_bits = 8
|
| 719 |
-
if down_init:
|
| 720 |
-
ih, iw = reader.read(16), reader.read(16)
|
| 721 |
-
init_bits = reader.read(4)
|
| 722 |
-
init = reader.read_array((ih, iw, 3), init_bits)
|
| 723 |
-
if init_bits < 8:
|
| 724 |
-
init = (init << (8 - init_bits)).astype(np.uint8)
|
| 725 |
-
canvas = np.asarray(Image.fromarray(init).resize((w, h), resample), dtype=np.int16)
|
| 726 |
-
if color_space == "YCbCr":
|
| 727 |
-
canvas = _rgb_to_ycbcr(canvas)
|
| 728 |
-
else:
|
| 729 |
-
canvas = np.full((h, w, 3), start, dtype=np.int16)
|
| 730 |
-
size_start, size_end = reader.read(16), reader.read(16)
|
| 731 |
-
vals = []
|
| 732 |
-
for _ in range(3):
|
| 733 |
-
flag = reader.read(1)
|
| 734 |
-
val = reader.read_float()
|
| 735 |
-
vals.append(-1.0 if flag else val)
|
| 736 |
-
sizes, _, _, _ = _decay(stroke_count, size_start, size_end, vals[0], vals[1], vals[2])
|
| 737 |
-
mlen = reader.read(9)
|
| 738 |
-
mult_list = tuple(reader.read_signed(9) for _ in range(mlen))
|
| 739 |
-
focus_warmup = reader.read(32)
|
| 740 |
-
focus_strokes, focus_max_bits, focus_pad = reader.read(20), reader.read(8), reader.read(8)
|
| 741 |
-
_ = reader.read(2)
|
| 742 |
-
cycle_mode = reader.read(3)
|
| 743 |
-
cycle_strokes = 0; cycle_warmup = 0
|
| 744 |
-
if cycle_mode:
|
| 745 |
-
cycle_strokes = reader.read(20); cycle_warmup = reader.read(32); _ = reader.read(2)
|
| 746 |
-
placement = reader.read(2)
|
| 747 |
-
seed = reader.read(64)
|
| 748 |
-
indices = np.zeros((stroke_count, 4), dtype=np.uint16)
|
| 749 |
-
focus_codes = np.full(stroke_count, -1, dtype=np.int64)
|
| 750 |
-
focus_bits = np.zeros(stroke_count, dtype=np.uint8)
|
| 751 |
-
cycle_codes = np.full((stroke_count, 3), -1, dtype=np.int64)
|
| 752 |
-
counters = [focus_warmup // 3] * 3
|
| 753 |
-
selector = [0, 1, 2]
|
| 754 |
-
timer = cycle_warmup
|
| 755 |
-
mbits = int(np.ceil(np.log2(mlen)))
|
| 756 |
-
for i in range(stroke_count):
|
| 757 |
-
channel = selector[i % 3]
|
| 758 |
-
if counters[channel] <= 0:
|
| 759 |
-
bits = _focus_bitcount(h, w, int(sizes[i]), focus_max_bits)
|
| 760 |
-
focus_bits[i] = bits
|
| 761 |
-
focus_codes[i] = reader.read(bits) if bits else 0
|
| 762 |
-
counters[channel] = focus_strokes
|
| 763 |
-
if cycle_mode and timer <= 0:
|
| 764 |
-
selector = [reader.read(2), reader.read(2), reader.read(2)]
|
| 765 |
-
cycle_codes[i] = selector
|
| 766 |
-
timer = cycle_strokes
|
| 767 |
-
for k in range(4):
|
| 768 |
-
indices[i, k] = reader.read(mbits)
|
| 769 |
-
counters[channel] -= 1
|
| 770 |
-
if cycle_mode:
|
| 771 |
-
timer -= 1
|
| 772 |
-
canvas = _decode_loop(canvas, sizes, np.asarray(mult_list, dtype=np.int16), indices, focus_codes, focus_bits, cycle_codes, seed, placement, focus_strokes, focus_warmup, focus_pad, cycle_mode, cycle_strokes, cycle_warmup)
|
| 773 |
-
final = np.clip(canvas, 0, 255)
|
| 774 |
-
final = _ycbcr_to_rgb(final) if color_space == "YCbCr" else final.astype(np.uint8)
|
| 775 |
-
img = Image.fromarray(final)
|
| 776 |
-
if original_size is not None:
|
| 777 |
-
img = img.resize(original_size, resample)
|
| 778 |
-
if not return_result:
|
| 779 |
-
return img
|
| 780 |
-
cfg = PBCConfig(stroke_count=stroke_count, mult_list=mult_list, color_space=color_space, downsample_initialize=down_init, downsample_initialize_bits=init_bits, resample=resample_name, placement_mode=list(PLACEMENT)[placement], seed=seed)
|
| 781 |
-
return img, cfg
|
| 782 |
-
|
| 783 |
-
@staticmethod
|
| 784 |
-
def encode_file(input_path: str, output_path: str, config: Optional[PBCConfig] = None, **overrides) -> PBCResult:
|
| 785 |
-
result = PBC.compress(input_path, config, **overrides)
|
| 786 |
-
result.save(output_path)
|
| 787 |
-
return result
|
| 788 |
-
|
| 789 |
-
save = encode_file
|
| 790 |
-
|
| 791 |
-
@staticmethod
|
| 792 |
-
def decode_file(input_path: str, output_path: Optional[str] = None) -> Image.Image:
|
| 793 |
-
img = PBC.decompress(input_path)
|
| 794 |
-
if output_path:
|
| 795 |
-
img.save(output_path)
|
| 796 |
-
return img
|
| 797 |
-
|
| 798 |
-
load = decode_file
|
| 799 |
-
|
| 800 |
-
@staticmethod
|
| 801 |
-
def preload_numba() -> None:
|
| 802 |
-
img = Image.fromarray(np.random.randint(0, 256, (16, 16, 3), dtype=np.uint8))
|
| 803 |
-
PBC.compress(img, stroke_count=8, downsample_initialize=False, focus_warmup=1.0, channel_cycle=False)
|
| 804 |
-
|
| 805 |
-
def _generate_multlist(bit_count: int = 2, min_value: int = -10, max_value: int = 20, mode: str = "Stable_Uniform"):
|
| 806 |
-
n = 1 << int(bit_count)
|
| 807 |
-
if n <= 1:
|
| 808 |
-
return [int(round((min_value + max_value) / 2))]
|
| 809 |
-
if mode == "Random":
|
| 810 |
-
rng = np.random.default_rng(2003)
|
| 811 |
-
vals = sorted(set(int(x) for x in rng.integers(min_value, max_value + 1, size=max(n * 4, 16))))
|
| 812 |
-
if len(vals) >= n:
|
| 813 |
-
return vals[:n]
|
| 814 |
-
return [int(round(x)) for x in np.linspace(min_value, max_value, n)]
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
PBC.generate_multlist = staticmethod(_generate_multlist)
|
| 818 |
-
PBC2_4 = PBC
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
PBC2_4_stream_patch.py
DELETED
|
@@ -1,286 +0,0 @@
|
|
| 1 |
-
"""Fast streaming compatibility patch for PBC2_4.py.
|
| 2 |
-
|
| 3 |
-
Use either:
|
| 4 |
-
import PBC2_4_stream_patch
|
| 5 |
-
after importing PBC2_4, or paste this file at the bottom of PBC2_4.py.
|
| 6 |
-
"""
|
| 7 |
-
|
| 8 |
-
from __future__ import annotations
|
| 9 |
-
|
| 10 |
-
from dataclasses import replace
|
| 11 |
-
import numpy as np
|
| 12 |
-
from PIL import Image
|
| 13 |
-
|
| 14 |
-
from PBC2_4 import (
|
| 15 |
-
PBC,
|
| 16 |
-
PBCConfig,
|
| 17 |
-
RESAMPLE,
|
| 18 |
-
PLACEMENT,
|
| 19 |
-
CYCLE,
|
| 20 |
-
CRITERIA,
|
| 21 |
-
_prepare_config,
|
| 22 |
-
_start_color,
|
| 23 |
-
_rgb_to_ycbcr,
|
| 24 |
-
_ycbcr_to_rgb,
|
| 25 |
-
_decay,
|
| 26 |
-
_focus_bitcount,
|
| 27 |
-
_select_focus_exact,
|
| 28 |
-
_select_focus_sampled,
|
| 29 |
-
_focus_bounds,
|
| 30 |
-
_coords,
|
| 31 |
-
_apply_tile,
|
| 32 |
-
_channel_selector,
|
| 33 |
-
_pack,
|
| 34 |
-
)
|
| 35 |
-
|
| 36 |
-
_RESAMPLE_FROM_PIL = {
|
| 37 |
-
int(Image.Resampling.NEAREST): "nearest",
|
| 38 |
-
int(Image.Resampling.BOX): "box",
|
| 39 |
-
int(Image.Resampling.BILINEAR): "bilinear",
|
| 40 |
-
int(Image.Resampling.HAMMING): "hamming",
|
| 41 |
-
int(Image.Resampling.BICUBIC): "bicubic",
|
| 42 |
-
int(Image.Resampling.LANCZOS): "lanczos",
|
| 43 |
-
}
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def _generate_multlist(bit_count: int = 2, min_value: int = -10, max_value: int = 20, mode: str = "Stable_Uniform"):
|
| 47 |
-
n = 1 << int(bit_count)
|
| 48 |
-
if n <= 1:
|
| 49 |
-
return [int(round((min_value + max_value) / 2))]
|
| 50 |
-
if mode == "Random":
|
| 51 |
-
rng = np.random.default_rng(2003)
|
| 52 |
-
vals = sorted(set(int(x) for x in rng.integers(min_value, max_value + 1, size=max(n * 8, 32))))
|
| 53 |
-
if len(vals) >= n:
|
| 54 |
-
return vals[:n]
|
| 55 |
-
return [int(round(x)) for x in np.linspace(min_value, max_value, n)]
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
def _normalize_kwargs(kwargs):
|
| 59 |
-
kwargs = dict(kwargs)
|
| 60 |
-
kwargs.pop("display_autos", None)
|
| 61 |
-
kwargs.pop("use_numba", None)
|
| 62 |
-
kwargs.pop("save_path", None)
|
| 63 |
-
|
| 64 |
-
if "decay_params" in kwargs:
|
| 65 |
-
decay = kwargs.pop("decay_params") or {}
|
| 66 |
-
kwargs.setdefault("decay_cutoff", decay.get("cutoff", -1))
|
| 67 |
-
kwargs.setdefault("decay_softness", decay.get("softness", -1))
|
| 68 |
-
kwargs.setdefault("decay_progress", decay.get("progress", -1))
|
| 69 |
-
|
| 70 |
-
aliases = {
|
| 71 |
-
"strokes_per_quadrant": "focus_strokes",
|
| 72 |
-
"quadrant_warmup_time": "focus_warmup",
|
| 73 |
-
"quadrant_max_bits": "focus_max_bits",
|
| 74 |
-
"quadrant_padding": "focus_padding",
|
| 75 |
-
"quadrant_selection_criteria": "focus_criteria",
|
| 76 |
-
"strokes_per_channel_cycle": "channel_cycle_strokes",
|
| 77 |
-
"channel_cycle_warmup_time": "channel_cycle_warmup",
|
| 78 |
-
"cycle_selection_criteria": "channel_cycle_criteria",
|
| 79 |
-
}
|
| 80 |
-
for old, new in aliases.items():
|
| 81 |
-
if old in kwargs:
|
| 82 |
-
kwargs.setdefault(new, kwargs.pop(old))
|
| 83 |
-
|
| 84 |
-
if kwargs.get("channel_cycle") == "123":
|
| 85 |
-
kwargs["channel_cycle"] = "Default"
|
| 86 |
-
|
| 87 |
-
if "downsample_alg" in kwargs:
|
| 88 |
-
alg = kwargs.pop("downsample_alg")
|
| 89 |
-
if isinstance(alg, str):
|
| 90 |
-
kwargs.setdefault("resample", alg.lower())
|
| 91 |
-
else:
|
| 92 |
-
kwargs.setdefault("resample", _RESAMPLE_FROM_PIL.get(int(alg), "bicubic"))
|
| 93 |
-
|
| 94 |
-
if "mult_list" in kwargs:
|
| 95 |
-
kwargs["mult_list"] = tuple(int(x) for x in kwargs["mult_list"])
|
| 96 |
-
|
| 97 |
-
return kwargs
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
def _compress_stream(
|
| 101 |
-
img_pil=None,
|
| 102 |
-
stream_interval: int = 100,
|
| 103 |
-
save_filename=None,
|
| 104 |
-
config: PBCConfig | None = None,
|
| 105 |
-
**kwargs,
|
| 106 |
-
):
|
| 107 |
-
"""Single-pass streaming encoder.
|
| 108 |
-
|
| 109 |
-
This mirrors PBC.compress setup, then runs the stroke loop once and yields
|
| 110 |
-
intermediate canvas frames every `stream_interval` strokes. It does not
|
| 111 |
-
recompress from scratch per frame.
|
| 112 |
-
"""
|
| 113 |
-
if img_pil is None:
|
| 114 |
-
img_pil = kwargs.pop("img", None)
|
| 115 |
-
if img_pil is None:
|
| 116 |
-
return
|
| 117 |
-
|
| 118 |
-
cfg = replace(config or PBCConfig(), **_normalize_kwargs(kwargs))
|
| 119 |
-
pil = Image.open(img_pil).convert("RGB") if isinstance(img_pil, str) else Image.fromarray(img_pil).convert("RGB") if isinstance(img_pil, np.ndarray) else img_pil.convert("RGB")
|
| 120 |
-
original_size = pil.size
|
| 121 |
-
cfg = _prepare_config(original_size, cfg)
|
| 122 |
-
resample = RESAMPLE[cfg.resample]
|
| 123 |
-
|
| 124 |
-
work_pil = pil
|
| 125 |
-
if cfg.downsample_rate > 1:
|
| 126 |
-
work_pil = pil.resize((max(1, int(pil.width / cfg.downsample_rate)), max(1, int(pil.height / cfg.downsample_rate))), resample)
|
| 127 |
-
|
| 128 |
-
target = np.asarray(work_pil, dtype=np.int16)
|
| 129 |
-
if cfg.color_space == "YCbCr":
|
| 130 |
-
target = _rgb_to_ycbcr(target)
|
| 131 |
-
h, w = target.shape[:2]
|
| 132 |
-
start = _start_color(target, cfg)
|
| 133 |
-
|
| 134 |
-
init = np.empty((0, 0, 3), dtype=np.uint8)
|
| 135 |
-
init_store = init
|
| 136 |
-
if cfg.downsample_initialize:
|
| 137 |
-
ih = max(1, int(h / cfg.downsample_initialize_rate))
|
| 138 |
-
iw = max(1, int(w / cfg.downsample_initialize_rate))
|
| 139 |
-
init = np.asarray(work_pil.resize((iw, ih), resample), dtype=np.uint8)
|
| 140 |
-
if cfg.downsample_initialize_bits < 8:
|
| 141 |
-
init = ((init >> (8 - cfg.downsample_initialize_bits)) << (8 - cfg.downsample_initialize_bits)).astype(np.uint8)
|
| 142 |
-
init_store = (init >> (8 - cfg.downsample_initialize_bits)).astype(np.uint8)
|
| 143 |
-
else:
|
| 144 |
-
init_store = init
|
| 145 |
-
canvas = np.asarray(Image.fromarray(init).resize((w, h), resample), dtype=np.int16)
|
| 146 |
-
if cfg.color_space == "YCbCr":
|
| 147 |
-
canvas = _rgb_to_ycbcr(canvas)
|
| 148 |
-
else:
|
| 149 |
-
canvas = np.full((h, w, 3), start, dtype=np.int16)
|
| 150 |
-
|
| 151 |
-
s0, s1 = cfg.size_range
|
| 152 |
-
if s0 == -1:
|
| 153 |
-
s0 = 0.3 + (1 / 1.00095) ** (cfg.stroke_count + 7000)
|
| 154 |
-
if s1 == -1:
|
| 155 |
-
s1 = 0.01 + (1 / 1.00015) ** (cfg.stroke_count + 10200)
|
| 156 |
-
sizes, cutoff, soft, prog = _decay(
|
| 157 |
-
cfg.stroke_count,
|
| 158 |
-
int(s0 * (min(h, w) - 2)) + 2,
|
| 159 |
-
int(s1 * (min(h, w) - 2)) + 2,
|
| 160 |
-
cfg.decay_cutoff,
|
| 161 |
-
cfg.decay_softness,
|
| 162 |
-
cfg.decay_progress,
|
| 163 |
-
)
|
| 164 |
-
|
| 165 |
-
if cfg.focus_mode == "sampled" or (cfg.focus_mode == "auto" and min(h, w) >= cfg.focus_sample_threshold):
|
| 166 |
-
focus_mode_id = 2
|
| 167 |
-
elif cfg.focus_mode in ("auto", "exact"):
|
| 168 |
-
focus_mode_id = 1
|
| 169 |
-
else:
|
| 170 |
-
raise ValueError("focus_mode must be 'auto', 'exact', or 'sampled'")
|
| 171 |
-
|
| 172 |
-
mults = np.asarray(cfg.mult_list, dtype=np.int16)
|
| 173 |
-
indices = np.zeros((cfg.stroke_count, 4), dtype=np.uint16)
|
| 174 |
-
focus_codes = np.full(cfg.stroke_count, -1, dtype=np.int64)
|
| 175 |
-
focus_bits = np.zeros(cfg.stroke_count, dtype=np.uint8)
|
| 176 |
-
cycle_codes = np.full((cfg.stroke_count, 3), -1, dtype=np.int64)
|
| 177 |
-
|
| 178 |
-
focus_warmup = int(cfg.focus_warmup * cfg.stroke_count)
|
| 179 |
-
cycle_warmup = int(cfg.channel_cycle_warmup * cfg.stroke_count)
|
| 180 |
-
focus_counters = [focus_warmup // 3] * 3
|
| 181 |
-
active_focus_codes = [0, 0, 0]
|
| 182 |
-
active_focus_bits = [0, 0, 0]
|
| 183 |
-
selector = [0, 1, 2]
|
| 184 |
-
cycle_timer = cycle_warmup
|
| 185 |
-
state = np.uint64(cfg.seed)
|
| 186 |
-
|
| 187 |
-
cycle_mode = CYCLE[cfg.channel_cycle]
|
| 188 |
-
placement = PLACEMENT[cfg.placement_mode]
|
| 189 |
-
stream_interval = max(1, int(stream_interval))
|
| 190 |
-
next_stream = 0
|
| 191 |
-
last_yield = -1
|
| 192 |
-
approx_header_bits = 512 + (init_store.size * cfg.downsample_initialize_bits if cfg.downsample_initialize else 0)
|
| 193 |
-
mult_bits = int(np.ceil(np.log2(len(cfg.mult_list))))
|
| 194 |
-
|
| 195 |
-
for i in range(cfg.stroke_count):
|
| 196 |
-
channel = selector[i % 3]
|
| 197 |
-
size = int(sizes[i])
|
| 198 |
-
target_layer = target[:, :, channel]
|
| 199 |
-
canvas_layer = canvas[:, :, channel]
|
| 200 |
-
|
| 201 |
-
if focus_counters[channel] <= 0:
|
| 202 |
-
bits = int(_focus_bitcount(h, w, size, cfg.focus_max_bits))
|
| 203 |
-
if focus_mode_id == 2:
|
| 204 |
-
code = int(_select_focus_sampled(target_layer, canvas_layer, h, w, bits, cfg.focus_sample_side))
|
| 205 |
-
else:
|
| 206 |
-
code = int(_select_focus_exact(target_layer, canvas_layer, h, w, bits, CRITERIA[cfg.focus_criteria]))
|
| 207 |
-
active_focus_codes[channel] = code
|
| 208 |
-
active_focus_bits[channel] = bits
|
| 209 |
-
focus_codes[i] = code
|
| 210 |
-
focus_bits[i] = bits
|
| 211 |
-
focus_counters[channel] = cfg.focus_strokes
|
| 212 |
-
|
| 213 |
-
if cycle_mode != 0 and cycle_timer <= 0:
|
| 214 |
-
order = _channel_selector(target, canvas, cycle_mode, CRITERIA[cfg.channel_cycle_criteria])
|
| 215 |
-
selector = [int(order[0]), int(order[1]), int(order[2])]
|
| 216 |
-
cycle_codes[i, 0], cycle_codes[i, 1], cycle_codes[i, 2] = selector[0], selector[1], selector[2]
|
| 217 |
-
cycle_timer = cfg.channel_cycle_strokes
|
| 218 |
-
|
| 219 |
-
if active_focus_bits[channel] > 0:
|
| 220 |
-
rs, cs, re, ce = _focus_bounds(h, w, size, active_focus_codes[channel], active_focus_bits[channel], cfg.focus_padding)
|
| 221 |
-
else:
|
| 222 |
-
rs, cs, re, ce = 0, 0, h - size, w - size
|
| 223 |
-
|
| 224 |
-
state, row, col = _coords(state, i, placement, rs, cs, re, ce, size)
|
| 225 |
-
state = np.uint64(state)
|
| 226 |
-
row = int(row)
|
| 227 |
-
col = int(col)
|
| 228 |
-
half = size // 2
|
| 229 |
-
|
| 230 |
-
indices[i, 0] = _apply_tile(target_layer, canvas_layer, row, row + half, col, col + half, mults)
|
| 231 |
-
indices[i, 1] = _apply_tile(target_layer, canvas_layer, row, row + half, col + half, col + size, mults)
|
| 232 |
-
indices[i, 2] = _apply_tile(target_layer, canvas_layer, row + half, row + size, col, col + half, mults)
|
| 233 |
-
indices[i, 3] = _apply_tile(target_layer, canvas_layer, row + half, row + size, col + half, col + size, mults)
|
| 234 |
-
|
| 235 |
-
focus_counters[channel] -= 1
|
| 236 |
-
if cycle_mode != 0:
|
| 237 |
-
cycle_timer -= 1
|
| 238 |
-
|
| 239 |
-
if i >= next_stream:
|
| 240 |
-
next_stream = i + stream_interval
|
| 241 |
-
last_yield = i
|
| 242 |
-
frame = np.clip(canvas, 0, 255)
|
| 243 |
-
frame = _ycbcr_to_rgb(frame) if cfg.color_space == "YCbCr" else frame.astype(np.uint8)
|
| 244 |
-
frame_pil = Image.fromarray(frame)
|
| 245 |
-
if cfg.downsample_rate > 1:
|
| 246 |
-
frame_pil = frame_pil.resize(original_size, resample)
|
| 247 |
-
yield frame_pil, f"Processed {i + 1}/{cfg.stroke_count} strokes. {((i + 1) / cfg.stroke_count) * 100:.2f}%", approx_header_bits + (i + 1) * 4 * mult_bits, []
|
| 248 |
-
|
| 249 |
-
final = np.clip(canvas, 0, 255)
|
| 250 |
-
final = _ycbcr_to_rgb(final) if cfg.color_space == "YCbCr" else final.astype(np.uint8)
|
| 251 |
-
final_img_pil = Image.fromarray(final)
|
| 252 |
-
if cfg.downsample_rate > 1:
|
| 253 |
-
final_img_pil = final_img_pil.resize(original_size, resample)
|
| 254 |
-
|
| 255 |
-
data, header_bits, total_bits = _pack(
|
| 256 |
-
cfg,
|
| 257 |
-
w,
|
| 258 |
-
h,
|
| 259 |
-
original_size,
|
| 260 |
-
sizes,
|
| 261 |
-
((cfg.decay_cutoff == -1, cutoff), (cfg.decay_softness == -1, soft), (cfg.decay_progress == -1, prog)),
|
| 262 |
-
start,
|
| 263 |
-
init_store,
|
| 264 |
-
(indices, focus_codes, focus_bits, cycle_codes),
|
| 265 |
-
)
|
| 266 |
-
|
| 267 |
-
if save_filename not in (None, False, -1):
|
| 268 |
-
with open(save_filename, "wb") as f:
|
| 269 |
-
f.write(data)
|
| 270 |
-
|
| 271 |
-
out = np.asarray(final_img_pil, dtype=np.uint8)
|
| 272 |
-
src = np.asarray(pil, dtype=np.uint8)
|
| 273 |
-
losses = [int(np.mean((src[:, :, c].astype(np.float32) - out[:, :, c].astype(np.float32)) ** 2)) for c in range(3)]
|
| 274 |
-
orig_bits = pil.size[0] * pil.size[1] * 3 * 8
|
| 275 |
-
bit_stats = "\n========================\nBITSTREAM STATS:\n"
|
| 276 |
-
bit_stats += f"Header: {header_bits} bits\n"
|
| 277 |
-
bit_stats += f"Strokes: {total_bits - header_bits} bits\n"
|
| 278 |
-
bit_stats += f"Total: {total_bits / 8 / 1024:.2f} KB from {orig_bits / 8 / 1024:.2f} KB original ({(total_bits / orig_bits) * 100:.2f}% size, {orig_bits / total_bits:.2f}x compression)\n"
|
| 279 |
-
bit_stats += "========================\n"
|
| 280 |
-
|
| 281 |
-
if last_yield != cfg.stroke_count - 1:
|
| 282 |
-
yield final_img_pil, bit_stats, total_bits, losses
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
PBC.generate_multlist = staticmethod(_generate_multlist)
|
| 286 |
-
PBC.compress_stream = staticmethod(_compress_stream)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server.py
CHANGED
|
@@ -11,18 +11,20 @@ from fastapi.staticfiles import StaticFiles
|
|
| 11 |
from PIL import Image
|
| 12 |
import numpy as np
|
| 13 |
|
| 14 |
-
from
|
| 15 |
-
import PBC2_4_stream_patch # registers PBC.generate_multlist and PBC.compress_stream
|
| 16 |
|
| 17 |
-
app = FastAPI(title="PBC Demo")
|
| 18 |
|
| 19 |
-
|
| 20 |
-
"Lanczos":
|
| 21 |
-
"Bicubic":
|
| 22 |
-
"Bilinear":
|
| 23 |
-
"Nearest":
|
| 24 |
}
|
| 25 |
|
|
|
|
|
|
|
|
|
|
| 26 |
DEMO_MULT_LIST = list(PBC.generate_multlist(7, -255, 255, "Stable_Uniform"))
|
| 27 |
|
| 28 |
|
|
@@ -32,8 +34,9 @@ def _png_b64(img: Image.Image) -> str:
|
|
| 32 |
return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
|
| 33 |
|
| 34 |
|
| 35 |
-
def _pbc_b64(
|
| 36 |
-
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def _f(v, d):
|
|
@@ -51,74 +54,6 @@ def _truthy(v):
|
|
| 51 |
return str(v).lower() == "true"
|
| 52 |
|
| 53 |
|
| 54 |
-
def _channel_cycle(v):
|
| 55 |
-
return "Default" if v == "123" else v
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
def _manual_kwargs(
|
| 59 |
-
stroke_count,
|
| 60 |
-
downsample_initialize_rate,
|
| 61 |
-
downsample_initialize,
|
| 62 |
-
size_range_start,
|
| 63 |
-
size_range_end,
|
| 64 |
-
color_space,
|
| 65 |
-
downsample_rate,
|
| 66 |
-
downsample_alg,
|
| 67 |
-
start_mode,
|
| 68 |
-
decay_mode,
|
| 69 |
-
decay_cutoff,
|
| 70 |
-
decay_softness,
|
| 71 |
-
decay_progress,
|
| 72 |
-
mult_list,
|
| 73 |
-
strokes_per_quadrant,
|
| 74 |
-
quadrant_warmup_time,
|
| 75 |
-
quadrant_max_bits,
|
| 76 |
-
quadrant_padding,
|
| 77 |
-
quadrant_selection_criteria,
|
| 78 |
-
channel_cycle,
|
| 79 |
-
strokes_per_channel_cycle,
|
| 80 |
-
channel_cycle_warmup_time,
|
| 81 |
-
cycle_selection_criteria,
|
| 82 |
-
focus_mode,
|
| 83 |
-
focus_sample_side,
|
| 84 |
-
focus_sample_threshold,
|
| 85 |
-
downsample_initialize_bits,
|
| 86 |
-
):
|
| 87 |
-
try:
|
| 88 |
-
mlist = tuple(int(x) for x in ast.literal_eval(mult_list))
|
| 89 |
-
assert mlist
|
| 90 |
-
except (ValueError, SyntaxError, AssertionError, TypeError):
|
| 91 |
-
mlist = (-10, 0, 5, 20)
|
| 92 |
-
|
| 93 |
-
return dict(
|
| 94 |
-
stroke_count=_i(stroke_count, -1),
|
| 95 |
-
size_range=(_f(size_range_start, 0.3), _f(size_range_end, 0.01)),
|
| 96 |
-
mult_list=mlist,
|
| 97 |
-
start_mode=start_mode,
|
| 98 |
-
decay_cutoff=-1.0 if decay_mode == "Auto" else _f(decay_cutoff, 0.5),
|
| 99 |
-
decay_softness=-1.0 if decay_mode == "Auto" else _f(decay_softness, 0.5),
|
| 100 |
-
decay_progress=-1.0 if decay_mode == "Auto" else _f(decay_progress, 0.5),
|
| 101 |
-
focus_strokes=_i(strokes_per_quadrant, 100),
|
| 102 |
-
focus_warmup=_f(quadrant_warmup_time, 0.5),
|
| 103 |
-
focus_max_bits=_i(quadrant_max_bits, 8),
|
| 104 |
-
focus_padding=_i(quadrant_padding, 4),
|
| 105 |
-
focus_criteria=quadrant_selection_criteria,
|
| 106 |
-
focus_mode=focus_mode,
|
| 107 |
-
focus_sample_side=_i(focus_sample_side, 384),
|
| 108 |
-
focus_sample_threshold=_i(focus_sample_threshold, 1536),
|
| 109 |
-
channel_cycle=_channel_cycle(channel_cycle),
|
| 110 |
-
channel_cycle_strokes=_i(strokes_per_channel_cycle, 100),
|
| 111 |
-
channel_cycle_warmup=_f(channel_cycle_warmup_time, 0.9),
|
| 112 |
-
channel_cycle_criteria=cycle_selection_criteria,
|
| 113 |
-
color_space=color_space,
|
| 114 |
-
downsample_rate=_f(downsample_rate, -1),
|
| 115 |
-
downsample_initialize=_truthy(downsample_initialize),
|
| 116 |
-
downsample_initialize_rate=_f(downsample_initialize_rate, 16),
|
| 117 |
-
downsample_initialize_bits=_i(downsample_initialize_bits, 8),
|
| 118 |
-
resample=RESAMPLE_NAME.get(downsample_alg, "bicubic"),
|
| 119 |
-
)
|
| 120 |
-
|
| 121 |
-
|
| 122 |
@app.get("/api/multlist")
|
| 123 |
def multlist(bit_count: int = 2, min: int = -10, max: int = 20, mode: str = "Stable_Uniform"):
|
| 124 |
return {"list": list(PBC.generate_multlist(bit_count, min, max, mode))}
|
|
@@ -151,10 +86,6 @@ async def compress(
|
|
| 151 |
strokes_per_channel_cycle: str = Form("100"),
|
| 152 |
channel_cycle_warmup_time: str = Form("0.9"),
|
| 153 |
cycle_selection_criteria: str = Form("Min"),
|
| 154 |
-
focus_mode: str = Form("auto"),
|
| 155 |
-
focus_sample_side: str = Form("384"),
|
| 156 |
-
focus_sample_threshold: str = Form("1536"),
|
| 157 |
-
downsample_initialize_bits: str = Form("8"),
|
| 158 |
):
|
| 159 |
raw_bytes = await image.read()
|
| 160 |
img = Image.open(io.BytesIO(raw_bytes)).convert("RGB")
|
|
@@ -167,56 +98,57 @@ async def compress(
|
|
| 167 |
stroke_count=_i(stroke_count, -1),
|
| 168 |
downsample_initialize=_truthy(downsample_initialize),
|
| 169 |
downsample_initialize_rate=_f(downsample_initialize_rate, 16),
|
| 170 |
-
downsample_initialize_bits=_i(downsample_initialize_bits, 8),
|
| 171 |
)
|
| 172 |
-
else:
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
| 201 |
)
|
| 202 |
|
| 203 |
timer = time.time()
|
| 204 |
-
|
| 205 |
elapsed = time.time() - timer
|
| 206 |
|
| 207 |
-
|
| 208 |
a = np.asarray(img, dtype=np.float32)
|
| 209 |
-
b = np.asarray(reconstructed.resize(img.size), dtype=np.float32)
|
| 210 |
mse = float(np.mean((a - b) ** 2))
|
| 211 |
psnr = 10 * math.log10(255.0 ** 2 / mse) if mse > 0 else 99.0
|
| 212 |
|
| 213 |
original_raw = w * h * 3
|
| 214 |
-
compressed = len(
|
| 215 |
|
| 216 |
return JSONResponse({
|
| 217 |
"original_image": _png_b64(img),
|
| 218 |
"reconstructed_image": _png_b64(reconstructed),
|
| 219 |
-
"pbc_base64": _pbc_b64(
|
| 220 |
"width": w,
|
| 221 |
"height": h,
|
| 222 |
"original_raw_kb": round(original_raw / 1024, 2),
|
|
@@ -227,7 +159,7 @@ async def compress(
|
|
| 227 |
"mse": round(mse, 1),
|
| 228 |
"psnr": round(psnr, 2),
|
| 229 |
"time_seconds": round(elapsed, 2),
|
| 230 |
-
"params": {"mode": mode, **{k: (list(v) if isinstance(v, tuple) else v) for k, v in kwargs.items()}},
|
| 231 |
})
|
| 232 |
|
| 233 |
|
|
@@ -235,18 +167,12 @@ async def compress(
|
|
| 235 |
async def stream_compress(image: UploadFile = File(...), downsample_initialize: str = Form("false")):
|
| 236 |
raw = await image.read()
|
| 237 |
img = Image.open(io.BytesIO(raw)).convert("RGB")
|
|
|
|
| 238 |
|
| 239 |
def gen():
|
| 240 |
for item in PBC.compress_stream(
|
| 241 |
-
img_pil=img,
|
| 242 |
-
|
| 243 |
-
mult_list=tuple(DEMO_MULT_LIST),
|
| 244 |
-
stroke_count=-1,
|
| 245 |
-
stream_interval=150,
|
| 246 |
-
downsample_initialize=_truthy(downsample_initialize),
|
| 247 |
-
downsample_rate=1,
|
| 248 |
-
focus_warmup=1.0,
|
| 249 |
-
channel_cycle=False,
|
| 250 |
):
|
| 251 |
frame = item[0]
|
| 252 |
if isinstance(frame, Image.Image):
|
|
@@ -258,8 +184,11 @@ async def stream_compress(image: UploadFile = File(...), downsample_initialize:
|
|
| 258 |
@app.post("/api/decode")
|
| 259 |
async def decode(file: UploadFile = File(...)):
|
| 260 |
raw = await file.read()
|
|
|
|
|
|
|
|
|
|
| 261 |
timer = time.time()
|
| 262 |
-
img = PBC.decompress(
|
| 263 |
elapsed = time.time() - timer
|
| 264 |
|
| 265 |
w, h = img.size
|
|
|
|
| 11 |
from PIL import Image
|
| 12 |
import numpy as np
|
| 13 |
|
| 14 |
+
from PBC2_3 import PBC
|
|
|
|
| 15 |
|
| 16 |
+
app = FastAPI(title="PBC Compression Demo")
|
| 17 |
|
| 18 |
+
RESAMPLE = {
|
| 19 |
+
"Lanczos": Image.LANCZOS,
|
| 20 |
+
"Bicubic": Image.BICUBIC,
|
| 21 |
+
"Bilinear": Image.BILINEAR,
|
| 22 |
+
"Nearest": Image.NEAREST,
|
| 23 |
}
|
| 24 |
|
| 25 |
+
# High-resolution multiplier list (bit count 7, range -255..255) for the landing
|
| 26 |
+
# teaser. Compression rate is irrelevant there, so a richer palette just makes the
|
| 27 |
+
# streamed build look better without costing extra time.
|
| 28 |
DEMO_MULT_LIST = list(PBC.generate_multlist(7, -255, 255, "Stable_Uniform"))
|
| 29 |
|
| 30 |
|
|
|
|
| 34 |
return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
|
| 35 |
|
| 36 |
|
| 37 |
+
def _pbc_b64(bitstream: str) -> str:
|
| 38 |
+
b_data, pad_len = PBC._bits_to_bytes(bitstream)
|
| 39 |
+
return base64.b64encode(bytes([pad_len]) + bytes(b_data)).decode()
|
| 40 |
|
| 41 |
|
| 42 |
def _f(v, d):
|
|
|
|
| 54 |
return str(v).lower() == "true"
|
| 55 |
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
@app.get("/api/multlist")
|
| 58 |
def multlist(bit_count: int = 2, min: int = -10, max: int = 20, mode: str = "Stable_Uniform"):
|
| 59 |
return {"list": list(PBC.generate_multlist(bit_count, min, max, mode))}
|
|
|
|
| 86 |
strokes_per_channel_cycle: str = Form("100"),
|
| 87 |
channel_cycle_warmup_time: str = Form("0.9"),
|
| 88 |
cycle_selection_criteria: str = Form("Min"),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
):
|
| 90 |
raw_bytes = await image.read()
|
| 91 |
img = Image.open(io.BytesIO(raw_bytes)).convert("RGB")
|
|
|
|
| 98 |
stroke_count=_i(stroke_count, -1),
|
| 99 |
downsample_initialize=_truthy(downsample_initialize),
|
| 100 |
downsample_initialize_rate=_f(downsample_initialize_rate, 16),
|
|
|
|
| 101 |
)
|
| 102 |
+
else: # Manual
|
| 103 |
+
decay = {"cutoff": -1, "softness": -1, "progress": -1} if decay_mode == "Auto" else {
|
| 104 |
+
"cutoff": _f(decay_cutoff, 0.5),
|
| 105 |
+
"softness": _f(decay_softness, 0.5),
|
| 106 |
+
"progress": _f(decay_progress, 0.5),
|
| 107 |
+
}
|
| 108 |
+
try:
|
| 109 |
+
mlist = [int(x) for x in ast.literal_eval(mult_list)]
|
| 110 |
+
assert mlist
|
| 111 |
+
except (ValueError, SyntaxError, AssertionError, TypeError):
|
| 112 |
+
mlist = [-10, 0, 5, 20]
|
| 113 |
+
kwargs = dict(
|
| 114 |
+
stroke_count=_i(stroke_count, -1),
|
| 115 |
+
size_range=(_f(size_range_start, 0.3), _f(size_range_end, 0.01)),
|
| 116 |
+
mult_list=mlist,
|
| 117 |
+
start_mode=start_mode,
|
| 118 |
+
decay_params=decay,
|
| 119 |
+
strokes_per_quadrant=_i(strokes_per_quadrant, 100),
|
| 120 |
+
quadrant_warmup_time=_f(quadrant_warmup_time, 0.5),
|
| 121 |
+
quadrant_max_bits=_i(quadrant_max_bits, 8),
|
| 122 |
+
quadrant_padding=_i(quadrant_padding, 4),
|
| 123 |
+
quadrant_selection_criteria=quadrant_selection_criteria,
|
| 124 |
+
channel_cycle=channel_cycle,
|
| 125 |
+
strokes_per_channel_cycle=_i(strokes_per_channel_cycle, 100),
|
| 126 |
+
channel_cycle_warmup_time=_f(channel_cycle_warmup_time, 0.9),
|
| 127 |
+
cycle_selection_criteria=cycle_selection_criteria,
|
| 128 |
+
color_space=color_space,
|
| 129 |
+
downsample_rate=_f(downsample_rate, -1),
|
| 130 |
+
downsample_initialize=_truthy(downsample_initialize),
|
| 131 |
+
downsample_initialize_rate=_f(downsample_initialize_rate, 16),
|
| 132 |
+
downsample_alg=RESAMPLE.get(downsample_alg, Image.BICUBIC),
|
| 133 |
)
|
| 134 |
|
| 135 |
timer = time.time()
|
| 136 |
+
reconstructed, _stats, bitstream, _losses = PBC.compress(img_pil=img, save_filename=None, **kwargs)
|
| 137 |
elapsed = time.time() - timer
|
| 138 |
|
| 139 |
+
# Full-resolution MSE/PSNR: original vs the upsampled reconstruction.
|
| 140 |
a = np.asarray(img, dtype=np.float32)
|
| 141 |
+
b = np.asarray(reconstructed.convert("RGB").resize(img.size), dtype=np.float32)
|
| 142 |
mse = float(np.mean((a - b) ** 2))
|
| 143 |
psnr = 10 * math.log10(255.0 ** 2 / mse) if mse > 0 else 99.0
|
| 144 |
|
| 145 |
original_raw = w * h * 3
|
| 146 |
+
compressed = len(bitstream) / 8
|
| 147 |
|
| 148 |
return JSONResponse({
|
| 149 |
"original_image": _png_b64(img),
|
| 150 |
"reconstructed_image": _png_b64(reconstructed),
|
| 151 |
+
"pbc_base64": _pbc_b64(bitstream),
|
| 152 |
"width": w,
|
| 153 |
"height": h,
|
| 154 |
"original_raw_kb": round(original_raw / 1024, 2),
|
|
|
|
| 159 |
"mse": round(mse, 1),
|
| 160 |
"psnr": round(psnr, 2),
|
| 161 |
"time_seconds": round(elapsed, 2),
|
| 162 |
+
"params": {"mode": mode, **{k: (list(v) if isinstance(v, tuple) else v) for k, v in kwargs.items() if k not in ("downsample_alg", "decay_params")}},
|
| 163 |
})
|
| 164 |
|
| 165 |
|
|
|
|
| 167 |
async def stream_compress(image: UploadFile = File(...), downsample_initialize: str = Form("false")):
|
| 168 |
raw = await image.read()
|
| 169 |
img = Image.open(io.BytesIO(raw)).convert("RGB")
|
| 170 |
+
dsi = _truthy(downsample_initialize)
|
| 171 |
|
| 172 |
def gen():
|
| 173 |
for item in PBC.compress_stream(
|
| 174 |
+
img_pil=img, save_filename=None,
|
| 175 |
+
mult_list=DEMO_MULT_LIST, stream_interval=150,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
):
|
| 177 |
frame = item[0]
|
| 178 |
if isinstance(frame, Image.Image):
|
|
|
|
| 184 |
@app.post("/api/decode")
|
| 185 |
async def decode(file: UploadFile = File(...)):
|
| 186 |
raw = await file.read()
|
| 187 |
+
pad_len = raw[0]
|
| 188 |
+
bitstream = PBC._bytes_to_bits(raw[1:], pad_len)
|
| 189 |
+
|
| 190 |
timer = time.time()
|
| 191 |
+
img = PBC.decompress(bitstream).convert("RGB")
|
| 192 |
elapsed = time.time() - timer
|
| 193 |
|
| 194 |
w, h = img.size
|
static/app.js
CHANGED
|
@@ -344,7 +344,6 @@ function gotoView(v) {
|
|
| 344 |
const PARAMS = [
|
| 345 |
{ id: "stroke_count", label: "Stroke count", hint: "higher = better quality but slower and less compression", group: "Core", modes: ["Semi", "Manual"], type: "slider", min: 0, max: 200000, step: 1000, value: 40000, full: true },
|
| 346 |
{ id: "downsample_initialize_rate", label: "Downsample init rate", group: "Core", modes: ["Semi", "Manual"], type: "slider", min: 2, max: 32, step: 0.1, value: 16, disableToggle: true },
|
| 347 |
-
{ id: "downsample_initialize_bits", label: "Downsample init bits", hint: "8 = raw, 6–7 = smaller init layer", group: "Core", modes: ["Semi", "Manual"], type: "slider", min: 4, max: 8, step: 1, value: 8 },
|
| 348 |
|
| 349 |
{ id: "size_range_start", label: "Size range start", group: "Strokes", modes: ["Manual"], type: "slider", min: 0.001, max: 1, step: 0.001, value: 0.3 },
|
| 350 |
{ id: "size_range_end", label: "Size range end", group: "Strokes", modes: ["Manual"], type: "slider", min: 0.001, max: 1, step: 0.001, value: 0.01 },
|
|
@@ -365,15 +364,11 @@ const PARAMS = [
|
|
| 365 |
{ id: "mult_max", label: "Multiplier maximum", group: "Multiplier list", modes: ["Manual"], type: "slider", min: -255, max: 255, step: 1, value: 20 },
|
| 366 |
{ id: "mult_list", label: "Multiplier list", hint: "editable", group: "Multiplier list", modes: ["Manual"], type: "text", value: "[-10, 0, 5, 20]", gen: true },
|
| 367 |
|
| 368 |
-
{ id: "strokes_per_quadrant", label: "Strokes /
|
| 369 |
-
{ id: "quadrant_warmup_time", label: "
|
| 370 |
-
{ id: "quadrant_max_bits", label: "
|
| 371 |
-
{ id: "quadrant_padding", label: "
|
| 372 |
-
{ id: "quadrant_selection_criteria", label: "
|
| 373 |
-
|
| 374 |
-
{ id: "focus_mode", label: "Focus mode", hint: "auto uses sampled focus on large canvases", group: "Focus", modes: ["Manual"], type: "select", options: ["auto", "exact", "sampled"], value: "auto" },
|
| 375 |
-
{ id: "focus_sample_side", label: "Sampled focus side", group: "Focus", modes: ["Manual"], type: "slider", min: 128, max: 1024, step: 128, value: 384 },
|
| 376 |
-
{ id: "focus_sample_threshold", label: "Sampled focus threshold", group: "Focus", modes: ["Manual"], type: "slider", min: 512, max: 4096, step: 128, value: 1536 },
|
| 377 |
|
| 378 |
{ id: "channel_cycle", label: "Channel cycle strategy", group: "Channel cycle", modes: ["Manual"], type: "select", options: ["Smart", "Strict", "Balanced", "123"], value: "Smart" },
|
| 379 |
{ id: "strokes_per_channel_cycle", label: "Strokes / cycle", group: "Channel cycle", modes: ["Manual"], type: "slider", min: 10, max: 1000, step: 10, value: 100 },
|
|
|
|
| 344 |
const PARAMS = [
|
| 345 |
{ id: "stroke_count", label: "Stroke count", hint: "higher = better quality but slower and less compression", group: "Core", modes: ["Semi", "Manual"], type: "slider", min: 0, max: 200000, step: 1000, value: 40000, full: true },
|
| 346 |
{ id: "downsample_initialize_rate", label: "Downsample init rate", group: "Core", modes: ["Semi", "Manual"], type: "slider", min: 2, max: 32, step: 0.1, value: 16, disableToggle: true },
|
|
|
|
| 347 |
|
| 348 |
{ id: "size_range_start", label: "Size range start", group: "Strokes", modes: ["Manual"], type: "slider", min: 0.001, max: 1, step: 0.001, value: 0.3 },
|
| 349 |
{ id: "size_range_end", label: "Size range end", group: "Strokes", modes: ["Manual"], type: "slider", min: 0.001, max: 1, step: 0.001, value: 0.01 },
|
|
|
|
| 364 |
{ id: "mult_max", label: "Multiplier maximum", group: "Multiplier list", modes: ["Manual"], type: "slider", min: -255, max: 255, step: 1, value: 20 },
|
| 365 |
{ id: "mult_list", label: "Multiplier list", hint: "editable", group: "Multiplier list", modes: ["Manual"], type: "text", value: "[-10, 0, 5, 20]", gen: true },
|
| 366 |
|
| 367 |
+
{ id: "strokes_per_quadrant", label: "Strokes / quadrant", group: "Quadrants", modes: ["Manual"], type: "slider", min: 10, max: 1000, step: 10, value: 100 },
|
| 368 |
+
{ id: "quadrant_warmup_time", label: "Quadrant warmup", group: "Quadrants", modes: ["Manual"], type: "slider", min: 0, max: 1, step: 0.01, value: 0.5 },
|
| 369 |
+
{ id: "quadrant_max_bits", label: "Quadrant max bits", group: "Quadrants", modes: ["Manual"], type: "slider", min: 1, max: 32, step: 1, value: 8 },
|
| 370 |
+
{ id: "quadrant_padding", label: "Quadrant padding", group: "Quadrants", modes: ["Manual"], type: "slider", min: 0, max: 32, step: 1, value: 4 },
|
| 371 |
+
{ id: "quadrant_selection_criteria", label: "Quadrant selection", group: "Quadrants", modes: ["Manual"], type: "select", options: ["Sum", "Max", "Min"], value: "Sum" },
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
|
| 373 |
{ id: "channel_cycle", label: "Channel cycle strategy", group: "Channel cycle", modes: ["Manual"], type: "select", options: ["Smart", "Strict", "Balanced", "123"], value: "Smart" },
|
| 374 |
{ id: "strokes_per_channel_cycle", label: "Strokes / cycle", group: "Channel cycle", modes: ["Manual"], type: "slider", min: 10, max: 1000, step: 10, value: 100 },
|
static/index.html
CHANGED
|
@@ -16,7 +16,7 @@
|
|
| 16 |
<section id="landing" class="section landing">
|
| 17 |
<div class="landing-grid">
|
| 18 |
<div class="landing-left">
|
| 19 |
-
<p class="eyebrow">PBC · v2.
|
| 20 |
<h1 class="title">Probabilistic <em>Brush</em> Compression.</h1>
|
| 21 |
<p class="lede">
|
| 22 |
An unconventional lossy image compression algorithm. It compresses image
|
|
|
|
| 16 |
<section id="landing" class="section landing">
|
| 17 |
<div class="landing-grid">
|
| 18 |
<div class="landing-left">
|
| 19 |
+
<p class="eyebrow">PBC · v2.3</p>
|
| 20 |
<h1 class="title">Probabilistic <em>Brush</em> Compression.</h1>
|
| 21 |
<p class="lede">
|
| 22 |
An unconventional lossy image compression algorithm. It compresses image
|
static/styles.css
CHANGED
|
@@ -63,7 +63,7 @@ em{font-style:normal;color:var(--red);}
|
|
| 63 |
.roster-hint{font-family:'JetBrains Mono',monospace;font-size:11px;color:var(--faint);letter-spacing:.1em;margin:0;}
|
| 64 |
.roster-note{font-size:11px;color:var(--faint);opacity:.8;margin:0;text-align:center;max-width:340px;}
|
| 65 |
.roster-note .x{transition:opacity .2s;}
|
| 66 |
-
.landing-right.use-real .roster-note .x{text-decoration:line-through;opacity:.
|
| 67 |
.landing-right.use-real .roster-hint{visibility:hidden;}
|
| 68 |
.real-toggle{display:flex;align-items:center;gap:.45rem;font-size:11.5px;color:var(--dim);cursor:pointer;margin:.2rem 0 0;user-select:none;position:relative;z-index:2;}
|
| 69 |
.real-toggle input{accent-color:var(--red);width:14px;height:14px;cursor:pointer;}
|
|
|
|
| 63 |
.roster-hint{font-family:'JetBrains Mono',monospace;font-size:11px;color:var(--faint);letter-spacing:.1em;margin:0;}
|
| 64 |
.roster-note{font-size:11px;color:var(--faint);opacity:.8;margin:0;text-align:center;max-width:340px;}
|
| 65 |
.roster-note .x{transition:opacity .2s;}
|
| 66 |
+
.landing-right.use-real .roster-note .x{text-decoration:line-through;opacity:.2;}
|
| 67 |
.landing-right.use-real .roster-hint{visibility:hidden;}
|
| 68 |
.real-toggle{display:flex;align-items:center;gap:.45rem;font-size:11.5px;color:var(--dim);cursor:pointer;margin:.2rem 0 0;user-select:none;position:relative;z-index:2;}
|
| 69 |
.real-toggle input{accent-color:var(--red);width:14px;height:14px;cursor:pointer;}
|