cyclic-text-compressor 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.
alignment_mvp.py ADDED
@@ -0,0 +1,203 @@
1
+ """Command-line MVP for the 142857 cyclic-alignment text format."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import string
7
+ from pathlib import Path
8
+ from typing import Sequence
9
+
10
+ from pattern_library import (
11
+ CYCLIC,
12
+ DRIFT_ALIGNMENT_STREAM_MAGIC,
13
+ decode_alignment_stream,
14
+ decode_drift_alignment_stream,
15
+ encode_alignment_stream,
16
+ encode_drift_alignment_stream,
17
+ write_drift_alignment_stream_file,
18
+ write_alignment_stream_file,
19
+ )
20
+
21
+ SEED_SYMBOLS = "aeiou "
22
+ SEED_VALUES = (1, 4, 2, 8, 5, 7)
23
+ ESCAPED_ASCII_PUNCTUATION = frozenset("^`{}|~<>$")
24
+ MVP_SYMBOLS = SEED_SYMBOLS + "".join(
25
+ symbol
26
+ for symbol in string.ascii_letters + string.digits + string.punctuation + "\t\r\n"
27
+ if symbol not in SEED_SYMBOLS and symbol not in ESCAPED_ASCII_PUNCTUATION
28
+ )
29
+
30
+ PAIR_ALPHABET = tuple(
31
+ (cyclic_value, cypher_number)
32
+ for cyclic_value in CYCLIC
33
+ for cypher_number in range(1, 16)
34
+ )
35
+ SEED_PAIRS = tuple((cyclic_value, 1) for cyclic_value in SEED_VALUES)
36
+ ESCAPE_PAIR = PAIR_ALPHABET[-1]
37
+ _reserved_pairs = set(SEED_PAIRS) | {ESCAPE_PAIR}
38
+ _available_pairs = [pair for pair in PAIR_ALPHABET if pair not in _reserved_pairs]
39
+
40
+ SYMBOL_TO_PAIR = {
41
+ **dict(zip(SEED_SYMBOLS, SEED_PAIRS)),
42
+ **dict(zip(
43
+ (symbol for symbol in MVP_SYMBOLS if symbol not in SEED_SYMBOLS),
44
+ _available_pairs,
45
+ )),
46
+ }
47
+ PAIR_TO_SYMBOL = {pair: symbol for symbol, pair in SYMBOL_TO_PAIR.items()}
48
+ PAIR_TO_TOKEN = {pair: token for token, pair in enumerate(PAIR_ALPHABET)}
49
+
50
+ if len(MVP_SYMBOLS) != 89 or len(SYMBOL_TO_PAIR) != 89:
51
+ raise RuntimeError("the MVP symbol mapping must contain 89 direct symbols")
52
+
53
+
54
+ def text_to_pairs(text: str) -> list[tuple[int, int]]:
55
+ """Map MVP symbols directly and encode other Unicode code points as escapes."""
56
+ pairs: list[tuple[int, int]] = []
57
+ for symbol in text:
58
+ pair = SYMBOL_TO_PAIR.get(symbol)
59
+ if pair is not None:
60
+ pairs.append(pair)
61
+ continue
62
+
63
+ codepoint = ord(symbol)
64
+ if 0xD800 <= codepoint <= 0xDFFF:
65
+ raise ValueError("unpaired Unicode surrogates cannot be encoded")
66
+ digits = [0] * 4
67
+ remainder = codepoint
68
+ for index in range(len(digits) - 1, -1, -1):
69
+ remainder, digits[index] = divmod(remainder, len(PAIR_ALPHABET))
70
+ if remainder:
71
+ raise ValueError(f"Unicode code point is outside the MVP range: U+{codepoint:04X}")
72
+ pairs.append(ESCAPE_PAIR)
73
+ pairs.extend(PAIR_ALPHABET[digit] for digit in digits)
74
+ return pairs
75
+
76
+
77
+ def pairs_to_text(pairs: Sequence[tuple[int, int]]) -> str:
78
+ """Restore text from direct symbol pairs and fixed-width Unicode escapes."""
79
+ output: list[str] = []
80
+ index = 0
81
+ while index < len(pairs):
82
+ pair = pairs[index]
83
+ if pair != ESCAPE_PAIR:
84
+ symbol = PAIR_TO_SYMBOL.get(pair)
85
+ if symbol is None:
86
+ raise ValueError(f"unassigned MVP pair: {pair!r}")
87
+ output.append(symbol)
88
+ index += 1
89
+ continue
90
+
91
+ if index + 4 >= len(pairs):
92
+ raise ValueError("truncated Unicode escape")
93
+ codepoint = 0
94
+ for digit_pair in pairs[index + 1:index + 5]:
95
+ token = PAIR_TO_TOKEN.get(digit_pair)
96
+ if token is None:
97
+ raise ValueError(f"invalid Unicode escape digit: {digit_pair!r}")
98
+ codepoint = codepoint * len(PAIR_ALPHABET) + token
99
+ if codepoint > 0x10FFFF or 0xD800 <= codepoint <= 0xDFFF:
100
+ raise ValueError("Unicode escape is not a valid scalar value")
101
+ output.append(chr(codepoint))
102
+ index += 5
103
+ return "".join(output)
104
+
105
+
106
+ def encode_text(text: str, *, drift: bool = False) -> bytes:
107
+ """Encode text with the standard or 7-digit drift alignment format."""
108
+ pairs = text_to_pairs(text)
109
+ if drift:
110
+ return encode_drift_alignment_stream(pairs)
111
+ return encode_alignment_stream(pairs)
112
+
113
+
114
+ def decode_text(encoded: bytes) -> str:
115
+ """Decode either alignment format to the original text."""
116
+ if encoded.startswith(DRIFT_ALIGNMENT_STREAM_MAGIC):
117
+ pairs = decode_drift_alignment_stream(encoded)
118
+ else:
119
+ pairs = decode_alignment_stream(encoded)
120
+ return pairs_to_text(pairs)
121
+
122
+
123
+ def encode_text_file(
124
+ source: str | Path,
125
+ destination: str | Path,
126
+ *,
127
+ drift: bool = False,
128
+ ) -> dict[str, object]:
129
+ """Compress a UTF-8 text file and report savings against its original bytes."""
130
+ source_path = Path(source)
131
+ destination_path = Path(destination)
132
+ if source_path.resolve() == destination_path.resolve():
133
+ raise ValueError("source and destination paths must differ")
134
+
135
+ with source_path.open("r", encoding="utf-8", newline="") as source_file:
136
+ text = source_file.read()
137
+ pairs = text_to_pairs(text)
138
+ if drift:
139
+ stats = write_drift_alignment_stream_file(destination_path, pairs)
140
+ else:
141
+ stats = write_alignment_stream_file(destination_path, pairs)
142
+ source_bytes = len(text.encode("utf-8"))
143
+ encoded_bytes = destination_path.stat().st_size
144
+ saved_bytes = source_bytes - encoded_bytes
145
+ return {
146
+ **stats,
147
+ "source_utf8_bytes": source_bytes,
148
+ "saved_bytes_vs_source": saved_bytes,
149
+ "reduction_percent_vs_source": (
150
+ saved_bytes / source_bytes * 100 if source_bytes else 0.0
151
+ ),
152
+ }
153
+
154
+
155
+ def decode_text_file(source: str | Path, destination: str | Path) -> int:
156
+ """Rebuild a UTF-8 text file from an alignment binary file."""
157
+ source_path = Path(source)
158
+ destination_path = Path(destination)
159
+ if source_path.resolve() == destination_path.resolve():
160
+ raise ValueError("source and destination paths must differ")
161
+
162
+ text = decode_text(source_path.read_bytes())
163
+ with destination_path.open("w", encoding="utf-8", newline="") as output_file:
164
+ output_file.write(text)
165
+ return len(text)
166
+
167
+
168
+ def main(argv: Sequence[str] | None = None) -> int:
169
+ parser = argparse.ArgumentParser(
170
+ description="Encode or rebuild text using the 142857 alignment MVP."
171
+ )
172
+ commands = parser.add_subparsers(dest="command", required=True)
173
+ encode_parser = commands.add_parser("encode", help="compress a UTF-8 text file")
174
+ encode_parser.add_argument("source", type=Path)
175
+ encode_parser.add_argument("destination", type=Path)
176
+ encode_parser.add_argument(
177
+ "--drift",
178
+ action="store_true",
179
+ help="use the exact 1428570 seven-digit drift track",
180
+ )
181
+ decode_parser = commands.add_parser("decode", help="rebuild a UTF-8 text file")
182
+ decode_parser.add_argument("source", type=Path)
183
+ decode_parser.add_argument("destination", type=Path)
184
+ args = parser.parse_args(argv)
185
+
186
+ try:
187
+ if args.command == "encode":
188
+ stats = encode_text_file(args.source, args.destination, drift=args.drift)
189
+ print(
190
+ f"Encoded {stats['source_utf8_bytes']} UTF-8 bytes to "
191
+ f"{stats['encoded_bytes']} bytes "
192
+ f"({stats['reduction_percent_vs_source']:.1f}% reduction)."
193
+ )
194
+ else:
195
+ symbol_count = decode_text_file(args.source, args.destination)
196
+ print(f"Rebuilt {symbol_count} text symbols.")
197
+ except ValueError as error:
198
+ parser.error(str(error))
199
+ return 0
200
+
201
+
202
+ if __name__ == "__main__":
203
+ raise SystemExit(main())