nanohex 2.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nanohex/__init__.py ADDED
@@ -0,0 +1,220 @@
1
+ """NanoHex v2: palette-based image encoding with row-wise run-length encoding."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Iterable
8
+
9
+ from PIL import Image
10
+
11
+ _HEX_INDEX = re.compile(r"^[0-9A-Fa-f]$")
12
+ _HEX_COLOR = re.compile(r"^#[0-9A-Fa-f]{6}$")
13
+
14
+
15
+ class NanoHexError(ValueError):
16
+ """Raised when an NHX file or image cannot be processed."""
17
+
18
+
19
+ def _run_length_encode(row: Iterable[int]) -> str:
20
+ values = list(row)
21
+ if not values:
22
+ raise NanoHexError("Cannot encode an empty image row")
23
+ runs: list[str] = []
24
+ current = values[0]
25
+ count = 1
26
+ for value in values[1:]:
27
+ if value == current:
28
+ count += 1
29
+ else:
30
+ runs.append(f"{current:X}*{count}")
31
+ current, count = value, 1
32
+ runs.append(f"{current:X}*{count}")
33
+ return ":".join(runs)
34
+
35
+
36
+ def encode_image(input_path: str | Path, output_path: str | Path,
37
+ width: int = 32, height: int = 32, max_colors: int = 16) -> Path:
38
+ """Convert an image to NHX. Alpha is composited onto white before encoding."""
39
+ if width < 1 or height < 1:
40
+ raise NanoHexError("Width and height must be positive integers")
41
+ if not 1 <= max_colors <= 16:
42
+ raise NanoHexError("max_colors must be between 1 and 16 (NHX uses one hex digit per index)")
43
+
44
+ source = Path(input_path)
45
+ destination = Path(output_path)
46
+ try:
47
+ with Image.open(source) as opened:
48
+ rgba = opened.convert("RGBA")
49
+ background = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
50
+ flattened = Image.alpha_composite(background, rgba).convert("RGB")
51
+ resized = flattened.resize((width, height), Image.Resampling.NEAREST)
52
+ quantized = resized.quantize(colors=max_colors, method=Image.Quantize.MEDIANCUT)
53
+ indices = list(quantized.tobytes())
54
+ raw_palette = quantized.getpalette()
55
+ except (OSError, ValueError) as exc:
56
+ raise NanoHexError(f"Could not read or process image '{source}': {exc}") from exc
57
+
58
+ used_indices = sorted(set(indices))
59
+ if not used_indices:
60
+ raise NanoHexError("The input image contains no pixels")
61
+ palette: list[str] = []
62
+ remap: dict[int, int] = {}
63
+ for new_index, old_index in enumerate(used_indices):
64
+ offset = old_index * 3
65
+ rgb = raw_palette[offset:offset + 3]
66
+ if len(rgb) != 3:
67
+ raise NanoHexError("Image palette is incomplete")
68
+ palette.append("#{:02X}{:02X}{:02X}".format(*rgb))
69
+ remap[old_index] = new_index
70
+
71
+ rows: list[str] = []
72
+ for y in range(height):
73
+ row_indices = [remap[value] for value in indices[y * width:(y + 1) * width]]
74
+ rows.append(_run_length_encode(row_indices))
75
+
76
+ destination.parent.mkdir(parents=True, exist_ok=True)
77
+ content = ["@size", f"h={height}", f"w={width}", "", "@palette", *palette, "", "@data", *rows]
78
+ destination.write_text("\n".join(content) + "\n", encoding="utf-8", newline="\n")
79
+ return destination
80
+
81
+
82
+ def _parse_sections(text: str) -> tuple[int, int, list[str], list[str]]:
83
+ lines = text.splitlines()
84
+ sections: dict[str, list[str]] = {}
85
+ current: str | None = None
86
+ for line_number, raw in enumerate(lines, start=1):
87
+ line = raw.strip()
88
+ if line.startswith("@"):
89
+ if line not in ("@size", "@palette", "@data"):
90
+ raise NanoHexError(f"Line {line_number}: unknown section '{line}'")
91
+ if line in sections:
92
+ raise NanoHexError(f"Line {line_number}: duplicate section '{line}'")
93
+ current = line
94
+ sections[current] = []
95
+ elif current is not None:
96
+ if line:
97
+ sections[current].append(line)
98
+ elif line:
99
+ raise NanoHexError(f"Line {line_number}: content found before first section")
100
+
101
+ missing = [name for name in ("@size", "@palette", "@data") if name not in sections]
102
+ if missing:
103
+ raise NanoHexError("Missing required section(s): " + ", ".join(missing))
104
+
105
+ dimensions: dict[str, int] = {}
106
+ for entry in sections["@size"]:
107
+ if "=" not in entry:
108
+ raise NanoHexError(f"Invalid size entry '{entry}'; expected key=value")
109
+ key, value = (part.strip() for part in entry.split("=", 1))
110
+ if key not in ("w", "h") or key in dimensions:
111
+ raise NanoHexError(f"Invalid or duplicate size key '{key}'")
112
+ try:
113
+ dimensions[key] = int(value)
114
+ except ValueError as exc:
115
+ raise NanoHexError(f"Invalid integer for size '{key}': {value}") from exc
116
+ if set(dimensions) != {"w", "h"}:
117
+ raise NanoHexError("@size must define both w and h")
118
+ width, height = dimensions["w"], dimensions["h"]
119
+ if not (1 <= width <= 10000 and 1 <= height <= 10000):
120
+ raise NanoHexError("Canvas dimensions must be between 1 and 10000")
121
+ if width * height > 25_000_000:
122
+ raise NanoHexError("Canvas exceeds the 25-million-pixel safety limit")
123
+
124
+ palette = [entry.upper() for entry in sections["@palette"]]
125
+ if not 1 <= len(palette) <= 16:
126
+ raise NanoHexError("Palette must contain between 1 and 16 colours")
127
+ for color in palette:
128
+ if not _HEX_COLOR.fullmatch(color):
129
+ raise NanoHexError(f"Invalid palette colour '{color}'; expected #RRGGBB")
130
+
131
+ rows: list[str] = []
132
+ for row_number, line in enumerate(sections["@data"], start=1):
133
+ decoded = ""
134
+ for token in line.split(":"):
135
+ token = token.strip()
136
+ if not token:
137
+ raise NanoHexError(f"Data row {row_number}: empty run between separators")
138
+ if "*" in token:
139
+ if token.count("*") != 1:
140
+ raise NanoHexError(f"Data row {row_number}: malformed run '{token}'")
141
+ index, count_text = (part.strip() for part in token.split("*", 1))
142
+ if not _HEX_INDEX.fullmatch(index):
143
+ raise NanoHexError(f"Data row {row_number}: invalid palette index '{index}'")
144
+ try:
145
+ count = int(count_text)
146
+ except ValueError as exc:
147
+ raise NanoHexError(f"Data row {row_number}: invalid run length '{count_text}'") from exc
148
+ if count < 1 or count > width:
149
+ raise NanoHexError(f"Data row {row_number}: run length must be between 1 and {width}")
150
+ decoded += index.upper() * count
151
+ else:
152
+ if not token or any(not _HEX_INDEX.fullmatch(char) for char in token):
153
+ raise NanoHexError(f"Data row {row_number}: invalid pixel sequence '{token}'")
154
+ decoded += token.upper()
155
+ if len(decoded) > width:
156
+ raise NanoHexError(f"Data row {row_number}: expands beyond declared width {width}")
157
+ if len(decoded) != width:
158
+ raise NanoHexError(f"Data row {row_number}: expected {width} pixels, got {len(decoded)}")
159
+ for char in decoded:
160
+ if int(char, 16) >= len(palette):
161
+ raise NanoHexError(f"Data row {row_number}: palette index {char} is out of range")
162
+ rows.append(decoded)
163
+
164
+ if len(rows) != height:
165
+ raise NanoHexError(f"Expected {height} data rows, got {len(rows)}")
166
+ return width, height, palette, rows
167
+
168
+
169
+ def decode_image(input_path: str | Path, output_path: str | Path,
170
+ scale: int = 1) -> Path:
171
+ """Decode an NHX file and save an RGB image."""
172
+ if scale < 1:
173
+ raise NanoHexError("Scale must be a positive integer")
174
+ source, destination = Path(input_path), Path(output_path)
175
+ try:
176
+ text = source.read_text(encoding="utf-8")
177
+ except OSError as exc:
178
+ raise NanoHexError(f"Could not read NHX file '{source}': {exc}") from exc
179
+ width, height, palette, rows = _parse_sections(text)
180
+ rgb_palette = [tuple(bytes.fromhex(color[1:])) for color in palette]
181
+ pixels = [rgb_palette[int(index, 16)] for row in rows for index in row]
182
+ image = Image.new("RGB", (width, height))
183
+ image.putdata(pixels)
184
+ if scale != 1:
185
+ image = image.resize((width * scale, height * scale), Image.Resampling.NEAREST)
186
+ destination.parent.mkdir(parents=True, exist_ok=True)
187
+ try:
188
+ image.save(destination)
189
+ except OSError as exc:
190
+ raise NanoHexError(f"Could not save decoded image '{destination}': {exc}") from exc
191
+ return destination
192
+
193
+
194
+ def main() -> int:
195
+ parser = argparse.ArgumentParser(prog="nanohex", description="Encode and decode NanoHex (.nhx) images")
196
+ commands = parser.add_subparsers(dest="command", required=True)
197
+ enc = commands.add_parser("encode", help="Convert an image to NHX")
198
+ enc.add_argument("input", help="Input image path")
199
+ enc.add_argument("output", help="Output .nhx path")
200
+ enc.add_argument("--width", type=int, default=32)
201
+ enc.add_argument("--height", type=int, default=32)
202
+ enc.add_argument("--colors", type=int, default=16, help="Maximum palette colours (1-16)")
203
+ dec = commands.add_parser("decode", help="Convert NHX to an image")
204
+ dec.add_argument("input", help="Input .nhx path")
205
+ dec.add_argument("output", help="Output image path, e.g. decoded.png")
206
+ dec.add_argument("--scale", type=int, default=1, help="Nearest-neighbour integer enlargement")
207
+ args = parser.parse_args()
208
+ try:
209
+ if args.command == "encode":
210
+ result = encode_image(args.input, args.output, args.width, args.height, args.colors)
211
+ else:
212
+ result = decode_image(args.input, args.output, args.scale)
213
+ except NanoHexError as exc:
214
+ parser.exit(2, f"nanohex: error: {exc}\n")
215
+ print(f"Created {result}")
216
+ return 0
217
+
218
+
219
+ if __name__ == "__main__":
220
+ raise SystemExit(main())
nanohex/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from . import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,162 @@
1
+ Metadata-Version: 2.4
2
+ Name: nanohex
3
+ Version: 2.0.1
4
+ Summary: A lightweight palette-based image format using hexadecimal pixel indices and row-wise run-length encoding
5
+ Author: Ashutosh Acharya
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 NanoHex contributors
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/Ashutosh-377/NanoHex
29
+ Project-URL: Repository, https://github.com/Ashutosh-377/NanoHex
30
+ Project-URL: Issues, https://github.com/Ashutosh-377/NanoHex/issues
31
+ Keywords: image-format,image-encoding,image-decoding,rle,palette,pillow
32
+ Classifier: Development Status :: 4 - Beta
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: OS Independent
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3.10
38
+ Classifier: Programming Language :: Python :: 3.11
39
+ Classifier: Programming Language :: Python :: 3.12
40
+ Classifier: Programming Language :: Python :: 3.13
41
+ Classifier: Topic :: Multimedia :: Graphics
42
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
43
+ Requires-Python: >=3.10
44
+ Description-Content-Type: text/markdown
45
+ License-File: LICENSE
46
+ Requires-Dist: Pillow>=9.1.0
47
+ Dynamic: license-file
48
+
49
+ # NanoHex v2.0.1
50
+
51
+ NanoHex is a small palette-based raster image format. It stores a canvas size, a hexadecimal RGB palette, and pixel rows encoded with run-length encoding (RLE).
52
+
53
+ ## Features
54
+
55
+ - Configurable output dimensions (nearest-neighbour resizing).
56
+ - Adaptive palette quantisation with 1–16 colours.
57
+ - One hexadecimal digit per palette index.
58
+ - Row-wise RLE to represent repeated pixels compactly.
59
+ - Decoder validation for malformed sections, dimensions, colours, runs, and palette references.
60
+ - PNG (and other Pillow-supported image formats) input/output.
61
+ - Transparent input pixels are composited onto white; NHX v2 stores RGB colours only.
62
+
63
+ ## Requirements
64
+
65
+ - Python 3.10+
66
+ - Pillow 9.1+
67
+
68
+ Install NanoHex from PyPI:
69
+
70
+ ```bash
71
+ python -m pip install nanohex
72
+ ```
73
+
74
+ Alternatively, install from a source checkout:
75
+
76
+ ```bash
77
+ python -m pip install .
78
+ ```
79
+
80
+ ## Usage
81
+
82
+ Encode an image into a 32×32 NHX file using up to 16 colours:
83
+
84
+ ```bash
85
+ python -m pip install .
86
+ python -m nanohex encode input.png output.nhx
87
+ ```
88
+
89
+ Choose dimensions and palette size:
90
+
91
+ ```bash
92
+ python -m nanohex encode input.png output.nhx --width 64 --height 64 --colors 12
93
+ ```
94
+
95
+ Decode an NHX file:
96
+
97
+ ```bash
98
+ python -m nanohex decode output.nhx decoded.png
99
+ ```
100
+
101
+ Enlarge the decoded image by an integer factor using nearest-neighbour scaling:
102
+
103
+ ```bash
104
+ python -m nanohex decode output.nhx decoded.png --scale 10
105
+ ```
106
+
107
+ ## NHX file structure
108
+
109
+ An NHX file is UTF-8 text with three required sections, in any order:
110
+
111
+ ```text
112
+ @size
113
+ h=8
114
+ w=8
115
+
116
+ @palette
117
+ #FFFFFF
118
+ #000000
119
+ #af0000
120
+
121
+ @data
122
+ 0*8
123
+ 0*5:2*3
124
+ 1*3:2*5
125
+ ...
126
+ ```
127
+
128
+ ### `@size`
129
+
130
+ Defines positive integer canvas dimensions with `w` (width) and `h` (height). The decoder currently limits each dimension to 10,000 and the total canvas to 25 million pixels.
131
+
132
+ ### `@palette`
133
+
134
+ Contains 1–16 RGB colours in `#RRGGBB` notation. Palette entries are addressed by a single hexadecimal digit: `0`–`9`, `A`–`F`.
135
+
136
+ ### `@data`
137
+
138
+ Contains exactly `h` non-empty rows. Each row must expand to exactly `w` pixels. Runs use `INDEX*COUNT`, separated by colons. For example, `A*4:0*2` means four pixels using palette entry `A`, followed by two pixels using entry `0`.
139
+
140
+ For compatibility with earlier NanoHex files, rows containing an uncompressed sequence of hexadecimal indices are also accepted (for example, `0110`).
141
+
142
+ ## Compatibility and limitations
143
+
144
+ - v2.0.1 preserves the original `@size`, `@palette`, and `@data` layout and the original one-digit palette-index/RLE representation.
145
+ - Existing files using up to 16 palette entries and valid row data remain readable.
146
+ - Alpha/transparency is not represented in NHX; the encoder composites transparent pixels onto white.
147
+ - Animation, metadata, arbitrary colour profiles, and palettes larger than 16 colours are not supported.
148
+ - Encoding resizes to the requested dimensions before quantisation; decoding reconstructs the stored dimensions.
149
+
150
+ The full format definition is available in [docs/NHX_FORMAT.md](docs/NHX_FORMAT.md).
151
+
152
+ ## Tests
153
+
154
+ Run the test suite from the repository root:
155
+
156
+ ```bash
157
+ python -m unittest discover -s tests -v
158
+ ```
159
+
160
+ ## License
161
+
162
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,8 @@
1
+ nanohex/__init__.py,sha256=gafrHrh14LAUQE0cnIvWkpPoWt1yc2GUwsP1iuNv8GU,9745
2
+ nanohex/__main__.py,sha256=BHLi_-4Bx1gsZn-z6x7wECPn1YTxdc74y0deRea9FzY,45
3
+ nanohex-2.0.1.dist-info/licenses/LICENSE,sha256=5Bl3jPZsSR2Lc6L3rWcbsJ9NBdQZCK5phlyGI-4aw5g,1077
4
+ nanohex-2.0.1.dist-info/METADATA,sha256=iq16PAkuveYcmb2kO2OCyU0pUPKvDm96oFsqfepfEWE,5679
5
+ nanohex-2.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ nanohex-2.0.1.dist-info/entry_points.txt,sha256=BiDPKcNcq9OXZuhqoFFgLZ5PbdNcgS8s0DNQj-x0ZAg,41
7
+ nanohex-2.0.1.dist-info/top_level.txt,sha256=UaeY5g1KnsJ3P5OLOsc0RDaD3TxG2xKNIfnduORKTQQ,8
8
+ nanohex-2.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ nanohex = nanohex:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NanoHex contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ nanohex