project-ghostframe 0.1.0__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.
ghostframe.py ADDED
@@ -0,0 +1,338 @@
1
+ """PNG encoding and transport experiments for full-frame RGBA animations."""
2
+
3
+ import argparse
4
+ import hashlib
5
+ import io
6
+ import json
7
+ import struct
8
+ import zlib
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from PIL import Image, ImageChops
13
+
14
+ SIGNATURE = b"\x89PNG\r\n\x1a\n"
15
+ ARCHIVE = b"gfRs"
16
+ ARCHIVE_HEADER = struct.Struct(">4sHHHI32s")
17
+ MAX_FILE = 32 * 1024 * 1024
18
+ MAX_MOTION = 32 * 1024 * 1024
19
+ MAX_PIXELS = 4_000_000
20
+ MAX_FRAMES = 120
21
+
22
+
23
+ def digest(data):
24
+ return hashlib.sha256(data).hexdigest()
25
+
26
+
27
+ def rgba_length(width, height):
28
+ if not (0 < width <= 65535 and 0 < height <= 65535):
29
+ raise ValueError("Dimensions hors limites")
30
+ if width * height > MAX_PIXELS:
31
+ raise ValueError("Raster trop grand")
32
+ return width * height * 4
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Motion:
37
+ width: int
38
+ height: int
39
+ frames: tuple[bytes, ...]
40
+ delays: tuple[int, ...]
41
+ plays: int = 0
42
+
43
+ def __post_init__(self):
44
+ size = rgba_length(self.width, self.height)
45
+ if not 1 <= len(self.frames) <= MAX_FRAMES or len(self.frames) * size > MAX_MOTION:
46
+ raise ValueError("Nombre ou volume de trames hors limites")
47
+ if any(len(frame) != size for frame in self.frames):
48
+ raise ValueError("Dimensions de trames incohérentes")
49
+ if len(self.frames) != len(self.delays) or any(
50
+ not isinstance(ms, int) or not 1 <= ms <= 65535 for ms in self.delays
51
+ ):
52
+ raise ValueError("Délais entiers en millisecondes attendus")
53
+ if not 0 <= self.plays <= 0xFFFFFFFF:
54
+ raise ValueError("Nombre de lectures hors limites")
55
+
56
+ def fingerprint(self):
57
+ return {
58
+ "size": [self.width, self.height],
59
+ "frames": [digest(frame) for frame in self.frames],
60
+ "delays_ms": list(self.delays),
61
+ "plays": self.plays,
62
+ }
63
+
64
+
65
+ def png_chunk(kind, data):
66
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
67
+
68
+
69
+ def chunks(blob):
70
+ """Validate bounded PNG framing and return chunk types and payloads."""
71
+ if len(blob) > MAX_FILE or not blob.startswith(SIGNATURE):
72
+ raise ValueError("Signature ou taille PNG invalide")
73
+ stream = []
74
+ pos = len(SIGNATURE)
75
+ while pos + 12 <= len(blob):
76
+ length, kind = struct.unpack_from(">I4s", blob, pos)
77
+ end = pos + 12 + length
78
+ if end > len(blob) or not kind.isalpha() or not kind[2:3].isupper():
79
+ raise ValueError("Bloc PNG invalide")
80
+ data = blob[pos + 8:end - 4]
81
+ if zlib.crc32(kind + data) != struct.unpack_from(">I", blob, end - 4)[0]:
82
+ raise ValueError(f"CRC invalide pour {kind.decode('ascii')}")
83
+ if len(stream) == 8192:
84
+ raise ValueError("Trop de blocs PNG")
85
+ stream.append((kind, data))
86
+ pos = end
87
+ if kind == b"IEND":
88
+ break
89
+ kinds = [kind for kind, _ in stream]
90
+ if (
91
+ pos != len(blob) or not kinds or kinds[0] != b"IHDR"
92
+ or kinds[-1] != b"IEND" or stream[-1][1]
93
+ or kinds.count(b"IHDR") != 1 or len(stream[0][1]) != 13
94
+ or b"IDAT" not in kinds
95
+ ):
96
+ raise ValueError("Structure PNG incomplète")
97
+ first = kinds.index(b"IDAT")
98
+ if kinds[first:first + kinds.count(b"IDAT")] != [b"IDAT"] * kinds.count(b"IDAT"):
99
+ raise ValueError("Blocs IDAT non contigus")
100
+ rgba_length(*struct.unpack_from(">II", stream[0][1]))
101
+ return stream
102
+
103
+
104
+ def serialize(stream):
105
+ blob = SIGNATURE + b"".join(png_chunk(kind, data) for kind, data in stream)
106
+ if len(blob) > MAX_FILE:
107
+ raise ValueError("Fichier PNG trop grand")
108
+ return blob
109
+
110
+
111
+ def compressed_pixels(width, height, rgba):
112
+ if rgba_length(width, height) != len(rgba):
113
+ raise ValueError("Taille du raster incohérente")
114
+ stride = width * 4
115
+ rows = (b"\x00" + rgba[offset:offset + stride] for offset in range(0, len(rgba), stride))
116
+ return zlib.compress(b"".join(rows), level=9)
117
+
118
+
119
+ def header(width, height):
120
+ return b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)
121
+
122
+
123
+ def static_png(width, height, rgba):
124
+ return serialize([header(width, height), (b"IDAT", compressed_pixels(width, height, rgba)), (b"IEND", b"")])
125
+
126
+
127
+ def frame_region(width, height, frame, previous, full_pixels):
128
+ current = Image.frombytes("RGBA", (width, height), frame)
129
+ prior = Image.frombytes("RGBA", (width, height), previous)
130
+ box = ImageChops.difference(current, prior).getbbox(alpha_only=False)
131
+ left, top, right, bottom = box or (0, 0, 1, 1)
132
+ cropped_width, cropped_height = right - left, bottom - top
133
+ if (cropped_width, cropped_height) != (width, height):
134
+ compressed = compressed_pixels(cropped_width, cropped_height, current.crop((left, top, right, bottom)).tobytes())
135
+ if len(compressed) < len(full_pixels):
136
+ return cropped_width, cropped_height, left, top, compressed
137
+ return width, height, 0, 0, full_pixels
138
+
139
+
140
+ def apng(motion, poster=None, archive=False, sparse=False):
141
+ """Use a separate default image when poster is supplied."""
142
+ width, height = motion.width, motion.height
143
+ stream = [header(width, height), (b"acTL", struct.pack(">II", len(motion.frames), motion.plays))]
144
+ if poster is not None:
145
+ stream.append((b"IDAT", compressed_pixels(width, height, poster)))
146
+
147
+ sequence = 0
148
+ previous = None
149
+ for index, (frame, delay) in enumerate(zip(motion.frames, motion.delays, strict=True)):
150
+ region_width, region_height, x, y = width, height, 0, 0
151
+ pixels = compressed_pixels(width, height, frame)
152
+ if sparse and previous is not None:
153
+ region_width, region_height, x, y, pixels = frame_region(width, height, frame, previous, pixels)
154
+ control = struct.pack(">IIIIIHHBB", sequence, region_width, region_height, x, y, delay, 1000, 0, 0)
155
+ stream.append((b"fcTL", control))
156
+ sequence += 1
157
+ if index == 0 and poster is None:
158
+ stream.append((b"IDAT", pixels))
159
+ else:
160
+ stream.append((b"fdAT", struct.pack(">I", sequence) + pixels))
161
+ sequence += 1
162
+ previous = frame
163
+ if archive:
164
+ default = motion.frames[0] if poster is None else poster
165
+ stream.append((ARCHIVE, archive_payload(motion, default)))
166
+ stream.append((b"IEND", b""))
167
+ return serialize(stream)
168
+
169
+
170
+ def xor_frame(frame, previous):
171
+ return bytes(a ^ b for a, b in zip(frame, previous, strict=True))
172
+
173
+
174
+ def archive_payload(motion, poster):
175
+ if len(poster) != rgba_length(motion.width, motion.height):
176
+ raise ValueError("Dimensions de l’image par défaut incohérentes")
177
+ header_bytes = ARCHIVE_HEADER.pack(
178
+ b"GFR1", motion.width, motion.height, len(motion.frames), motion.plays,
179
+ hashlib.sha256(poster).digest(),
180
+ )
181
+ delays = struct.pack(f">{len(motion.delays)}H", *motion.delays)
182
+ residuals = [motion.frames[0]]
183
+ for previous, frame in zip(motion.frames, motion.frames[1:]):
184
+ residuals.append(xor_frame(frame, previous))
185
+ return header_bytes + zlib.compress(delays + b"".join(residuals), level=9)
186
+
187
+
188
+ def read_archive(payload):
189
+ if len(payload) <= ARCHIVE_HEADER.size:
190
+ raise ValueError("Archive Ghostframe tronquée")
191
+ magic, width, height, count, plays, poster_hash = ARCHIVE_HEADER.unpack_from(payload)
192
+ size = rgba_length(width, height)
193
+ if magic != b"GFR1" or not 1 <= count <= MAX_FRAMES or count * size > MAX_MOTION:
194
+ raise ValueError("En-tête Ghostframe invalide")
195
+ expected = count * (size + 2)
196
+ decoder = zlib.decompressobj()
197
+ decoded = decoder.decompress(payload[ARCHIVE_HEADER.size:], expected + 1)
198
+ if len(decoded) != expected or not decoder.eof or decoder.unused_data or decoder.unconsumed_tail:
199
+ raise ValueError("Taille ou flux Ghostframe invalide")
200
+ delays = struct.unpack_from(f">{count}H", decoded)
201
+ frames = []
202
+ for offset in range(count * 2, expected, size):
203
+ residual = decoded[offset:offset + size]
204
+ frames.append(xor_frame(residual, frames[-1]) if frames else residual)
205
+ return Motion(width, height, tuple(frames), delays, plays), poster_hash
206
+
207
+
208
+ def decoded_png(blob):
209
+ """Decode the default raster and, when present, full composited APNG frames."""
210
+ stream = chunks(blob)
211
+ with Image.open(io.BytesIO(blob), formats=["PNG"]) as image:
212
+ width, height = image.size
213
+ default = image.convert("RGBA").tobytes()
214
+ motion = None
215
+ if any(kind == b"acTL" for kind, _ in stream):
216
+ start = int(bool(image.info.get("default_image")))
217
+ count = image.n_frames - start
218
+ plays = image.info.get("loop", 0)
219
+ if not 1 <= count <= MAX_FRAMES or count * rgba_length(width, height) > MAX_MOTION:
220
+ raise ValueError("Animation hors limites")
221
+ frames, delays = [], []
222
+ for index in range(start, image.n_frames):
223
+ image.seek(index)
224
+ frames.append(image.convert("RGBA").tobytes())
225
+ delays.append(round(image.info["duration"]))
226
+ motion = Motion(width, height, tuple(frames), tuple(delays), plays)
227
+ return (width, height), default, motion
228
+
229
+
230
+ def inspect(blob):
231
+ stream = chunks(blob)
232
+ size, default, motion = decoded_png(blob)
233
+ return {
234
+ "sha256": digest(blob),
235
+ "bytes": len(blob),
236
+ "size": list(size),
237
+ "default_sha256": digest(default),
238
+ "chunks": [kind.decode("ascii") for kind, _ in stream],
239
+ "archive_bytes": sum(len(payload) for kind, payload in stream if kind == ARCHIVE),
240
+ "motion": None if motion is None else motion.fingerprint(),
241
+ }
242
+
243
+
244
+ def recover(blob):
245
+ archives = [payload for kind, payload in chunks(blob) if kind == ARCHIVE]
246
+ if len(archives) != 1:
247
+ raise ValueError("Un seul bloc Ghostframe est requis")
248
+ motion, poster_hash = read_archive(archives[0])
249
+ size, poster, _ = decoded_png(blob)
250
+ if size != (motion.width, motion.height) or hashlib.sha256(poster).digest() != poster_hash:
251
+ raise ValueError("Le raster par défaut ne correspond plus à l’archive")
252
+ separate_poster = None if poster == motion.frames[0] else poster
253
+ return apng(motion, poster=separate_poster)
254
+
255
+
256
+ def atlas(motion):
257
+ height = motion.height * len(motion.frames)
258
+ pixels = b"".join(motion.frames)
259
+ blob = static_png(motion.width, height, pixels)
260
+ manifest = motion.fingerprint()
261
+ manifest["atlas_rgba_sha256"] = digest(pixels)
262
+ return blob, manifest
263
+
264
+
265
+ def from_atlas(blob, manifest):
266
+ width, height = manifest["size"]
267
+ hashes = manifest["frames"]
268
+ stride = rgba_length(width, height)
269
+ size, pixels, native_motion = decoded_png(blob)
270
+ if native_motion is not None or size != (width, height * len(hashes)):
271
+ raise ValueError("Dimensions de l’atlas inattendues")
272
+ if digest(pixels) != manifest["atlas_rgba_sha256"]:
273
+ raise ValueError("Les pixels de l’atlas ont changé")
274
+ frames = tuple(pixels[start:start + stride] for start in range(0, len(pixels), stride))
275
+ if [digest(frame) for frame in frames] != hashes:
276
+ raise ValueError("Les trames de l’atlas ne correspondent pas au manifeste")
277
+ return Motion(width, height, frames, tuple(manifest["delays_ms"]), manifest["plays"])
278
+
279
+
280
+ def encode_files(paths, delay, plays):
281
+ size, frames = None, []
282
+ if len(paths) > MAX_FRAMES:
283
+ raise ValueError("Trop de fichiers source")
284
+ for path in paths:
285
+ frame_size, pixels, motion = decoded_png(path.read_bytes())
286
+ if motion is not None or (size is not None and size != frame_size):
287
+ raise ValueError("Des PNG statiques aux dimensions identiques sont requis")
288
+ size = frame_size
289
+ if (len(frames) + 1) * len(pixels) > MAX_MOTION:
290
+ raise ValueError("Séquence trop volumineuse")
291
+ frames.append(pixels)
292
+ return Motion(*size, tuple(frames), (delay,) * len(frames), plays)
293
+
294
+
295
+ def main():
296
+ parser = argparse.ArgumentParser(description=__doc__)
297
+ commands = parser.add_subparsers(dest="command", required=True)
298
+ encode = commands.add_parser("encode")
299
+ encode.add_argument("output", type=Path)
300
+ encode.add_argument("frames", type=Path, nargs="+")
301
+ encode.add_argument("--delay", type=int, default=250)
302
+ encode.add_argument("--plays", type=int, default=0)
303
+ encode.add_argument("--mode", choices=["apng", "dual", "atlas"], default="dual")
304
+ encode.add_argument("--sparse", action="store_true", help="Rectangles de différences APNG")
305
+ show = commands.add_parser("inspect")
306
+ show.add_argument("input", type=Path)
307
+ restore = commands.add_parser("recover")
308
+ restore.add_argument("input", type=Path)
309
+ restore.add_argument("output", type=Path)
310
+ split = commands.add_parser("from-atlas")
311
+ split.add_argument("input", type=Path)
312
+ split.add_argument("manifest", type=Path)
313
+ split.add_argument("output", type=Path)
314
+ args = parser.parse_args()
315
+ try:
316
+ if args.command == "inspect":
317
+ print(json.dumps(inspect(args.input.read_bytes()), indent=2))
318
+ elif args.command == "recover":
319
+ args.output.write_bytes(recover(args.input.read_bytes()))
320
+ elif args.command == "from-atlas":
321
+ manifest = json.loads(args.manifest.read_text(encoding="utf-8"))
322
+ args.output.write_bytes(apng(from_atlas(args.input.read_bytes(), manifest)))
323
+ else:
324
+ motion = encode_files(args.frames, args.delay, args.plays)
325
+ if args.mode == "atlas":
326
+ if args.sparse:
327
+ raise ValueError("--sparse exige un mode APNG ou dual")
328
+ blob, manifest = atlas(motion)
329
+ args.output.with_suffix(".json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
330
+ else:
331
+ blob = apng(motion, archive=args.mode == "dual", sparse=args.sparse)
332
+ args.output.write_bytes(blob)
333
+ except (ValueError, KeyError, TypeError, OSError, SyntaxError, EOFError, zlib.error, struct.error) as error:
334
+ parser.exit(2, f"{error}\n")
335
+
336
+
337
+ if __name__ == "__main__":
338
+ main()
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: project-ghostframe
3
+ Version: 0.1.0
4
+ Summary: PNG and APNG generation, inspection, and recovery tools from Residual Labs
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/zakariagharzouli/project-ghostframe
7
+ Project-URL: Issues, https://github.com/zakariagharzouli/project-ghostframe/issues
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: Pillow>=10
12
+ Dynamic: license-file
13
+
14
+ # Project Ghostframe for Python
15
+
16
+ English · [Français](#français) · [Project Ghostframe](https://github.com/zakariagharzouli/project-ghostframe)
17
+
18
+ `project-ghostframe` provides the `ghostframe` command and importable `ghostframe` module. It generates APNG files, inspects frame and archive metadata, and restores supported animations from a Ghostframe archive or atlas. It requires Python 3.10+ and Pillow. Ghostframe Replay is distributed as a standalone HTML app and a separate npm package.
19
+
20
+ Install from a repository checkout or from a built wheel.
21
+
22
+ ```sh
23
+ python -m pip install .
24
+ # Or install the distribution archive
25
+ python -m pip install ./project_ghostframe-0.1.0-py3-none-any.whl
26
+ ```
27
+
28
+ ```sh
29
+ python -m ghostframe encode animation.png frame-0.png frame-1.png --delay 350
30
+ python -m ghostframe inspect animation.png
31
+ python -m ghostframe recover animation.png recovered.png
32
+ ```
33
+
34
+ The default `dual` mode writes an APNG with a Ghostframe archive. `--mode apng` writes standard APNG frames, and `--mode atlas` produces a static PNG and a JSON manifest for `python -m ghostframe from-atlas`. `--sparse` uses delta rectangles for APNG or dual mode. Run `python -m ghostframe --help` for all commands. You can shorten `python -m ghostframe` to `ghostframe` when the installed console command is on your `PATH`.
35
+
36
+ ## Français
37
+
38
+ `project-ghostframe` fournit la commande `ghostframe` et le module Python du même nom. Il génère des APNG, inspecte les métadonnées des trames et restaure les animations prises en charge depuis une archive Ghostframe ou un atlas. Python 3.10+ et Pillow sont nécessaires. Ghostframe Replay est distribué séparément en HTML et via npm.
39
+
40
+ Depuis un clone du dépôt, saisir `python -m pip install .`. Avec la roue construite, saisir `python -m pip install ./project_ghostframe-0.1.0-py3-none-any.whl`. Les trois commandes de l’exemple utilisent des trames PNG à fournir localement. `python -m ghostframe --help` affiche toutes les commandes. Le raccourci `ghostframe` est disponible si la commande installée est dans le `PATH`.
41
+
42
+ Le mode par défaut `dual` écrit un APNG avec archive Ghostframe. `--mode apng` écrit un APNG standard. `--mode atlas` fournit une image PNG fixe et un manifeste JSON pour `python -m ghostframe from-atlas`. `--sparse` utilise des rectangles de différences en mode APNG ou dual.
@@ -0,0 +1,7 @@
1
+ ghostframe.py,sha256=X42UJw5pWbjAg5da65JSmAb5T6ahvtpCS2BUSWH9850,14089
2
+ project_ghostframe-0.1.0.dist-info/licenses/LICENSE,sha256=uwYcoDbJxEN_vxNawxH0VE7u3LPqErPNoQwgWrObOU0,1104
3
+ project_ghostframe-0.1.0.dist-info/METADATA,sha256=Na4bHjfPbzp7Ba37HmEdjpkXh9SYBhrsCMtFvT0qzIg,2809
4
+ project_ghostframe-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ project_ghostframe-0.1.0.dist-info/entry_points.txt,sha256=3zCCAMZAsmop-60iS5xMaz7DVvZHOlPV08FCF9sHE6g,47
6
+ project_ghostframe-0.1.0.dist-info/top_level.txt,sha256=qRRYg2BBraAuDEK_T10xhOItoQhAQaVny2QZwT5mUKs,11
7
+ project_ghostframe-0.1.0.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
+ ghostframe = ghostframe:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Residual Labs / Project Ghostframe 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
+ ghostframe