Spaces:
Sleeping
Sleeping
Download s2f/pixel_codec.py from ProgramComputer/Speech2Face: direct link, hf CLI and curl.
- Browser
- Download file 3.68 kB
-
https://huggingface.co/spaces/ProgramComputer/Speech2Face/resolve/main/s2f/pixel_codec.py
- Command line
-
hf download hf://spaces/ProgramComputer/Speech2Face/s2f/pixel_codec.py
-
curl -L -o pixel_codec.py https://huggingface.co/spaces/ProgramComputer/Speech2Face/resolve/main/s2f/pixel_codec.py
3.68 kB
| from __future__ import annotations | |
| import struct | |
| import zlib | |
| import numpy as np | |
| IMAGE_SIZE = 224 | |
| _PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" | |
| class EvidenceError(ValueError): | |
| pass | |
| def _chunk(kind: bytes, data: bytes) -> bytes: | |
| return ( | |
| struct.pack(">I", len(data)) | |
| + kind | |
| + data | |
| + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) | |
| ) | |
| def encode_png_rgb(image: np.ndarray) -> bytes: | |
| array = np.asarray(image) | |
| if array.dtype != np.uint8 or array.ndim != 3 or array.shape[2] != 3 or 0 in array.shape[:2]: | |
| raise EvidenceError("PNG encoder accepts uint8 RGB HWC only") | |
| height, width = array.shape[:2] | |
| scanlines = np.zeros((height, 1 + width * 3), dtype=np.uint8) | |
| scanlines[:, 1:] = np.ascontiguousarray(array).reshape(height, width * 3) | |
| header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) | |
| return ( | |
| _PNG_SIGNATURE | |
| + _chunk(b"IHDR", header) | |
| + _chunk(b"IDAT", zlib.compress(scanlines.tobytes(), 9)) | |
| + _chunk(b"IEND", b"") | |
| ) | |
| def decode_png_rgb(raw: bytes) -> np.ndarray: | |
| if not raw.startswith(_PNG_SIGNATURE): | |
| raise EvidenceError("PNG signature missing") | |
| idat: list[bytes] | |
| offset, header, idat, ended = len(_PNG_SIGNATURE), None, [], False | |
| while offset < len(raw): | |
| if offset + 8 > len(raw): | |
| raise EvidenceError("PNG chunk header truncated") | |
| (length,) = struct.unpack(">I", raw[offset : offset + 4]) | |
| kind = raw[offset + 4 : offset + 8] | |
| data = raw[offset + 8 : offset + 8 + length] | |
| crc = raw[offset + 8 + length : offset + 12 + length] | |
| if ( | |
| len(data) != length | |
| or len(crc) != 4 | |
| or struct.unpack(">I", crc)[0] != (zlib.crc32(kind + data) & 0xFFFFFFFF) | |
| ): | |
| raise EvidenceError("PNG chunk is truncated or fails its CRC") | |
| offset += 12 + length | |
| if kind == b"IHDR" and header is None and length == 13: | |
| header = struct.unpack(">IIBBBBB", data) | |
| elif kind == b"IDAT" and header is not None: | |
| idat.append(data) | |
| elif kind == b"IEND" and length == 0: | |
| ended = True | |
| break | |
| else: | |
| raise EvidenceError("Unexpected PNG chunk") | |
| if not ended or offset != len(raw) or header is None: | |
| raise EvidenceError("PNG stream is incomplete or has trailing bytes") | |
| width, height, depth, color, compression, filtering, interlace = header | |
| if ( | |
| (depth, color, compression, filtering, interlace) != (8, 2, 0, 0, 0) | |
| or not width | |
| or not height | |
| ): | |
| raise EvidenceError("Only non-interlaced 8-bit RGB PNG is accepted") | |
| data = zlib.decompress(b"".join(idat)) | |
| stride = 1 + width * 3 | |
| if len(data) != stride * height: | |
| raise EvidenceError("PNG pixel payload size mismatch") | |
| rows = np.frombuffer(data, dtype=np.uint8).reshape(height, stride) | |
| if np.any(rows[:, 0] != 0): | |
| raise EvidenceError("Only PNG filter type 0 is accepted") | |
| return rows[:, 1:].reshape(height, width, 3).copy() | |
| def quantize_rgb(chw: np.ndarray) -> tuple[np.ndarray, float]: | |
| array = np.asarray(chw) | |
| if array.dtype != np.float32 or array.shape != (3, IMAGE_SIZE, IMAGE_SIZE): | |
| raise EvidenceError("Image must be float32 CHW (3,224,224)") | |
| if not np.isfinite(array).all(): | |
| raise EvidenceError("Image contains non-finite values") | |
| outside = int(np.count_nonzero((array < 0.0) | (array > 1.0))) | |
| quantized = np.rint(np.clip(array.astype(np.float64), 0.0, 1.0) * 255.0).astype(np.uint8) | |
| return np.ascontiguousarray(quantized.transpose(1, 2, 0)), outside / array.size | |