Spaces:
Running on Zero
Running on Zero
Download demo/encode.py from robertren1/gpwm-simulation: direct link, hf CLI and curl.
- Browser
- Download file 2.38 kB
-
https://huggingface.co/spaces/robertren1/gpwm-simulation/resolve/main/demo/encode.py
- Command line
-
hf download hf://spaces/robertren1/gpwm-simulation/demo/encode.py
-
curl -L -o encode.py https://huggingface.co/spaces/robertren1/gpwm-simulation/resolve/main/demo/encode.py
2.38 kB
| """How frames travel to the page (the live demo's window format, pwm-live-drop livedrop/encode.py): a 16-byte header | |
| (magic b"PWMW", version, flags, frame count, first frame, point count; little endian), then the particles of every object | |
| on the table [frames, points, 3]: the first frame as uint16 in the table's BOX, then each frame's change from the one | |
| before as int16 (flags bit 1), on a grid 2^shift coarser (flags bits 4-7; shift 3 = 0.2 mm). For the Space the bytes | |
| are deflated (resting objects send zeros, which deflate all but removes) and sent as base64 text. | |
| """ | |
| import base64 | |
| import struct | |
| import zlib | |
| import numpy as np | |
| MAGIC = b"PWMW" | |
| VERSION = 1 | |
| HEADER = struct.Struct("<4sBBHII") # magic, version, flags, n_frames, first_frame, n_points | |
| LEVELS = 65535 | |
| DELTAS_FLAG = 2 | |
| SHIFT = 3 | |
| BOX = np.array([[-0.85, -0.85, -0.05], [0.85, 0.85, 1.0]]) # metres, the model's frame | |
| def quantize(frames, box=BOX): | |
| lo, hi = box | |
| return np.clip(np.round((np.asarray(frames, np.float64) - lo) / (hi - lo) * LEVELS), 0, LEVELS).astype(np.int32) | |
| def dequantize(q, box=BOX): | |
| lo, hi = box | |
| return lo + np.asarray(q, np.float64) / LEVELS * (hi - lo) | |
| def window_message(frames, first_frame, shift=SHIFT): | |
| """frames [L, N, 3] metres -> bytes.""" | |
| q = quantize(frames) >> shift | |
| L, N, _ = q.shape | |
| body = q[:1].astype("<u2").tobytes() + np.diff(q, axis=0).astype("<i2").tobytes() | |
| return HEADER.pack(MAGIC, VERSION, DELTAS_FLAG | (shift << 4), L, int(first_frame), N) + body | |
| def frames_text(frames, first_frame): | |
| """frames [L, N, 3] -> base64 of the deflated window message.""" | |
| return base64.b64encode(zlib.compress(window_message(frames, first_frame), 6)).decode() | |
| def read_window(message): | |
| magic, version, flags, L, first, N = HEADER.unpack_from(message, 0) | |
| if magic != MAGIC or version != VERSION: | |
| raise ValueError("not a window message") | |
| raw = np.frombuffer(message, dtype="<u2", offset=HEADER.size, count=L * N * 3).reshape(L, N, 3) | |
| shift = (flags >> 4) & 15 | |
| d = raw.view("<i2").astype(np.int32) | |
| c = np.concatenate([raw[:1].astype(np.int32), d[1:]]).cumsum(axis=0) | |
| q = ((c << shift) + ((1 << shift) >> 1)).clip(0, LEVELS) | |
| return dict(first_frame=first, frames=dequantize(q), points=N) | |
| def read_frames_text(text): | |
| return read_window(zlib.decompress(base64.b64decode(text))) | |