import sys
import os
import heapq
import argparse
import json
from collections import defaultdict
# ==========================================
# 1. Run-Length Encoding (RLE)
# ==========================================
class RLE:
"""
Compresses data by replacing consecutive identical characters
with the character and a count.
Format: [Char][Count]
"""
@staticmethod
def compress(data: bytes) -> bytes:
if not data:
return b""
compressed = bytearray()
count = 1
prev = data[0]
for byte in data[1:]:
if byte == prev and count < 255:
count += 1
else:
compressed.append(prev)
compressed.append(count)
prev = byte
count = 1
compressed.append(prev)
compressed.append(count)
return bytes(compressed)
@staticmethod
def decompress(data: bytes) -> bytes:
if not data:
return b""
decompressed = bytearray()
# Iterate 2 bytes at a time: (char, count)
for i in range(0, len(data), 2):
char = data[i]
count = data[i+1]
decompressed.extend([char] * count)
return bytes(decompressed)
# ==========================================
# 2. Huffman Coding
# ==========================================
class HuffmanNode:
def __init__(self, freq, char=None, left=None, right=None):
self.freq = freq
self.char = char
self.left = left
self.right = right
def __lt__(self, other):
return self.freq < other.freq
class Huffman:
"""
Lossless compression algorithm using variable-length coding
based on frequency analysis.
"""
@staticmethod
def _build_tree(data: bytes):
# 1. Calculate frequencies
freq = defaultdict(int)
for byte in data:
freq[byte] += 1
# 2. Create priority queue (min-heap)
heap = [HuffmanNode(f, c) for c, f in freq.items()]
heapq.heapify(heap)
# 3. Build tree
while len(heap) > 1:
left = heapq.heappop(heap)
right = heapq.heappop(heap)
merged = HuffmanNode(left.freq + right.freq, left=left, right=right)
heapq.heappush(heap, merged)
return heap[0] if heap else None
@staticmethod
def _generate_codes(root, current_code, codes):
if root is None:
return
if root.char is not None:
codes[root.char] = current_code
return
Huffman._generate_codes(root.left, current_code + "0", codes)
Huffman._generate_codes(root.right, current_code + "1", codes)
@staticmethod
def compress(data: bytes) -> bytes:
if not data:
return b""
root = Huffman._build_tree(data)
codes = {}
Huffman._generate_codes(root, "", codes)
# 1. Create bit string
bit_string = "".join([codes[byte] for byte in data])
# 2. Pad bit string to make it multiple of 8
padding = 8 - len(bit_string) % 8
bit_string += "0" * padding
# 3. Convert bit string to bytes
compressed_bytes = bytearray()
for i in range(0, len(bit_string), 8):
byte = int(bit_string[i:i+8], 2)
compressed_bytes.append(byte)
# 4. Serialize the dictionary (mapping) and padding info to JSON, then bytes
# In a real app, you'd write a binary header. Here we use JSON for simplicity.
header = {
"padding": padding,
"codes": {str(k): v for k, v in codes.items()} # Keys must be strings in JSON
}
header_bytes = json.dumps(header).encode('utf-8')
# Format: [Header Length (4 bytes)][Header JSON][Compressed Data]
final_output = bytearray()
final_output.extend(len(header_bytes).to_bytes(4, 'big'))
final_output.extend(header_bytes)
final_output.extend(compressed_bytes)
return bytes(final_output)
@staticmethod
def decompress(data: bytes) -> bytes:
if not data:
return b""
# 1. Parse Header
header_len = int.from_bytes(data[:4], 'big')
header_json = data[4 : 4 + header_len].decode('utf-8')
header = json.loads(header_json)
padding = header["padding"]
# Reverse mapping: code -> char
reverse_codes = {v: int(k) for k, v in header["codes"].items()}
compressed_data = data[4 + header_len:]
# 2. Convert bytes back to bit string
bit_string = "".join([format(byte, '08b') for byte in compressed_data])
# Remove padding
if padding > 0:
bit_string = bit_string[:-padding]
# 3. Decode
current_code = ""
decompressed = bytearray()
for bit in bit_string:
current_code += bit
if current_code in reverse_codes:
char = reverse_codes[current_code]
decompressed.append(char)
current_code = ""
return bytes(decompressed)
# ==========================================
# 3. LZW (Lempel-Ziv-Welch)
# ==========================================
class LZW:
"""
Dictionary-based compression. Replaces sequences of characters
with single codes.
"""
@staticmethod
def compress(data: bytes) -> bytes:
if not data:
return b""
# Initialize dictionary with byte values (0-255)
dictionary = {bytes([i]): i for i in range(256)}
current_code = 256
w = bytes()
result = []
# Max dictionary size (12-bit codes example)
MAX_DICT_SIZE = 4096
for byte in data:
wc = w + bytes([byte])
if wc in dictionary:
w = wc
else:
result.append(dictionary[w])
if current_code < MAX_DICT_SIZE:
dictionary[wc] = current_code
current_code += 1
w = bytes([byte])
if w:
result.append(dictionary[w])
# Encode result codes into bytes (assuming 12-bit codes -> 2 bytes per code for simplicity)
# Ideally, bit-packing is used here.
output = bytearray()
for code in result:
output.extend(code.to_bytes(2, 'big')) # 16 bits per code
return bytes(output)
@staticmethod
def decompress(data: bytes) -> bytes:
if not data:
return b""
# Initialize dictionary
dictionary = {i: bytes([i]) for i in range(256)}
current_code = 256
# Read codes (assuming 2 bytes per code)
codes = []
for i in range(0, len(data), 2):
chunk = data[i:i+2]
if len(chunk) < 2: break
codes.append(int.from_bytes(chunk, 'big'))
if not codes:
return b""
w = dictionary[codes[0]]
result = bytearray(w)
for k in codes[1:]:
if k in dictionary:
entry = dictionary[k]
elif k == current_code:
entry = w + bytes([w[0]])
else:
raise ValueError("Bad LZW compression code")
result.extend(entry)
if current_code < 4096:
dictionary[current_code] = w + bytes([entry[0]])
current_code += 1
w = entry
return bytes(result)
# ==========================================
# Main CLI Interface
# ==========================================
def main():
parser = argparse.ArgumentParser(description="Data Compression Utility")
parser.add_argument("mode", choices=["compress", "decompress"], help="Mode of operation")
parser.add_argument("input", help="Input file path")
parser.add_argument("output", help="Output file path")
parser.add_argument("--algo", choices=["rle", "huffman", "lzw"], default="huffman", help="Algorithm to use")
args = parser.parse_args()
# Select Algorithm
algorithms = {
"rle": RLE,
"huffman": Huffman,
"lzw": LZW
}
algo = algorithms[args.algo]
# Read Input
try:
with open(args.input, "rb") as f:
data = f.read()
except FileNotFoundError:
print(f"Error: File '{args.input}' not found.")
return
# Process
print(f"Processing with {args.algo.upper()}...")
original_size = len(data)
try:
if args.mode == "compress":
result = algo.compress(data)
new_size = len(result)
ratio = (1 - (new_size / original_size)) * 100 if original_size > 0 else 0
print(f"Original: {original_size} bytes")
print(f"Compressed: {new_size} bytes")
print(f"Space Saved: {ratio:.2f}%")
else:
result = algo.decompress(data)
print(f"Decompressed to {len(result)} bytes.")
# Write Output
with open(args.output, "wb") as f:
f.write(result)
print(f"Success! Output saved to '{args.output}'.")
except Exception as e:
print(f"Error during processing: {e}")
if __name__ == "__main__":
main()