The user wants a data compression utility with multiple algorithms. I'll create a comprehensive compression tool with a GUI that supports multiple compression algorithms including:
Huffman Coding - Lossless compression using frequency-based encoding
Run-Length Encoding (RLE) - Simple compression for repeated characters
I'll use Tkinter for the GUI as it's built-in, and implement the algorithms from scratch for educational purposes.
Let me create a comprehensive compression utility with a professional interface.
Data Compression Utility with Multiple Algorithms
I'll create a comprehensive data compression utility with a modern GUI that supports multiple compression algorithms including Huffman, RLE, LZ77, and LZW.
python
#!/usr/bin/env python3
"""
Data Compression Utility
Supports multiple compression algorithms: Huffman, RLE, LZ77, LZW
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
import heapq
import struct
import os
import time
from collections import defaultdict
from typing import Dict, Tuple, Optional, List
import threading
# ==================== Huffman Coding ====================
class HuffmanNode:
"""Node for Huffman tree"""
def __init__(self, char=None, freq=0, left=None, right=None):
self.char = char
self.freq = freq
self.left = left
self.right = right
def __lt__(self, other):
return self.freq < other.freq
class HuffmanCompression:
"""Huffman coding compression algorithm"""
@staticmethod
def build_frequency_table(data: bytes) -> Dict[int, int]:
"""Build frequency table for bytes"""
freq = defaultdict(int)
for byte in data:
freq[byte] += 1
return freq
@staticmethod
def build_huffman_tree(freq: Dict[int, int]) -> Optional[HuffmanNode]:
"""Build Huffman tree from frequency table"""
if not freq:
return None
heap = [HuffmanNode(char=char, freq=f) for char, f in freq.items()]
heapq.heapify(heap)
while len(heap) > 1:
left = heapq.heappop(heap)
right = heapq.heappop(heap)
merged = HuffmanNode(freq=left.freq + right.freq, left=left, right=right)
heapq.heappush(heap, merged)
return heap[0] if heap else None
@staticmethod
def build_codes(root: HuffmanNode) -> Dict[int, str]:
"""Build Huffman codes from tree"""
codes = {}
def traverse(node, code=""):
if node is None:
return
if node.char is not None:
codes[node.char] = code if code else "0"
return
traverse(node.left, code + "0")
traverse(node.right, code + "1")
traverse(root)
return codes
@staticmethod
def serialize_tree(root: HuffmanNode) -> bytes:
"""Serialize Huffman tree for storage"""
result = []
def serialize(node):
if node.char is not None:
result.append(b'\x01')
result.append(struct.pack('B', node.char))
else:
result.append(b'\x00')
serialize(node.left)
serialize(node.right)
if root:
serialize(root)
return b''.join(result)
@staticmethod
def deserialize_tree(data: bytes, index: int = 0) -> Tuple[Optional[HuffmanNode], int]:
"""Deserialize Huffman tree from bytes"""
if index >= len(data):
return None, index
if data[index] == 0x01:
char = data[index + 1]
return HuffmanNode(char=char), index + 2
else:
left, index = HuffmanCompression.deserialize_tree(data, index + 1)
right, index = HuffmanCompression.deserialize_tree(data, index)
return HuffmanNode(left=left, right=right), index
@staticmethod
def compress(data: bytes) -> bytes:
"""Compress data using Huffman coding"""
if not data:
return b''
# Build frequency table and Huffman tree
freq = HuffmanCompression.build_frequency_table(data)
tree = HuffmanCompression.build_huffman_tree(freq)
if tree is None:
return b''
# Build codes
codes = HuffmanCompression.build_codes(tree)
# Serialize tree
tree_data = HuffmanCompression.serialize_tree(tree)
# Encode data
encoded_bits = ''.join(codes[byte] for byte in data)
# Pad to make multiple of 8
padding = (8 - len(encoded_bits) % 8) % 8
encoded_bits += '0' * padding
# Convert to bytes
encoded_bytes = bytes(int(encoded_bits[i:i+8], 2)
for i in range(0, len(encoded_bits), 8))
# Pack header: tree size (4 bytes), padding (1 byte), original size (4 bytes)
header = struct.pack('>I', len(tree_data)) + struct.pack('B', padding) + struct.pack('>I', len(data))
return header + tree_data + encoded_bytes
@staticmethod
def decompress(data: bytes) -> bytes:
"""Decompress Huffman encoded data"""
if not data or len(data) < 9:
return b''
# Parse header
tree_size = struct.unpack('>I', data[0:4])[0]
padding = struct.unpack('B', data[4:5])[0]
original_size = struct.unpack('>I', data[5:9])[0]
# Deserialize tree
tree_data = data[9:9+tree_size]
tree, _ = HuffmanCompression.deserialize_tree(tree_data)
if tree is None:
return b''
# Decode data
encoded_bytes = data[9+tree_size:]
encoded_bits = ''.join(format(byte, '08b') for byte in encoded_bytes)
# Remove padding
if padding > 0:
encoded_bits = encoded_bits[:-padding]
# Traverse tree to decode
result = []
node = tree
for bit in encoded_bits:
node = node.right if bit == '1' else node.left
if node.char is not None:
result.append(node.char)
node = tree
if len(result) >= original_size:
break
return bytes(result)
# ==================== Run-Length Encoding ====================
class RLECompression:
"""Run-Length Encoding compression"""
# Special marker for RLE sequences
MARKER = 0xFF
@staticmethod
def compress(data: bytes) -> bytes:
"""Compress data using RLE"""
if not data:
return b''
result = []
i = 0
while i < len(data):
# Count consecutive same bytes
count = 1
while i + count < len(data) and data[i + count] == data[i] and count < 255:
count += 1
if count >= 4 or data[i] == RLECompression.MARKER:
# Use RLE encoding: MARKER, count, byte
result.append(RLECompression.MARKER)
result.append(count)
result.append(data[i])
i += count
else:
# Output literal bytes
for j in range(count):
if data[i + j] == RLECompression.MARKER:
result.append(RLECompression.MARKER)
result.append(1)
result.append(RLECompression.MARKER)
else:
result.append(data[i + j])
i += count
# Add header with original size
header = struct.pack('>I', len(data))
return header + bytes(result)
@staticmethod
def decompress(data: bytes) -> bytes:
"""Decompress RLE encoded data"""
if not data or len(data) < 4:
return b''
# Parse header
original_size = struct.unpack('>I', data[0:4])[0]
result = []
i = 4
while i < len(data):
if data[i] == RLECompression.MARKER:
if i + 2 >= len(data):
break
count = data[i + 1]
byte = data[i + 2]
result.extend([byte] * count)
i += 3
else:
result.append(data[i])
i += 1
return bytes(result[:original_size])
# ==================== LZ77 Compression ====================
class LZ77Compression:
"""LZ77 sliding window compression"""
WINDOW_SIZE = 4096 # 4KB sliding window
MAX_MATCH_LENGTH = 18
MIN_MATCH_LENGTH = 3
@staticmethod
def find_longest_match(data: bytes, pos: int) -> Tuple[int, int]:
"""Find longest match in sliding window"""
if pos < LZ77Compression.MIN_MATCH_LENGTH:
return 0, 0
best_offset = 0
best_length = 0
window_start = max(0, pos - LZ77Compression.WINDOW_SIZE)
max_length = min(LZ77Compression.MAX_MATCH_LENGTH, len(data) - pos)
for i in range(window_start, pos):
length = 0
while (length < max_length and
pos + length < len(data) and
data[i + length] == data[pos + length]):
length += 1
# Allow matching into the lookahead buffer
if i + length >= pos:
# Wrap around for repeating patterns
while (length < max_length and
pos + length < len(data) and
data[i + (length % (pos - i))] == data[pos + length]):
length += 1
break
if length >= LZ77Compression.MIN_MATCH_LENGTH and length > best_length:
best_offset = pos - i
best_length = length
return best_offset, best_length
@staticmethod
def compress(data: bytes) -> bytes:
"""Compress data using LZ77"""
if not data:
return b''
result = []
pos = 0
while pos < len(data):
offset, length = LZ77Compression.find_longest_match(data, pos)
if length >= LZ77Compression.MIN_MATCH_LENGTH:
# Encode as: 0 (flag), offset (2 bytes), length (1 byte)
result.append(0) # Match flag
result.extend(struct.pack('>H', offset))
result.append(length)
pos += length
else:
# Encode as: 1 (flag), literal byte
result.append(1) # Literal flag
result.append(data[pos])
pos += 1
# Add header
header = struct.pack('>I', len(data))
return header + bytes(result)
@staticmethod
def decompress(data: bytes) -> bytes:
"""Decompress LZ77 encoded data"""
if not data or len(data) < 4:
return b''
original_size = struct.unpack('>I', data[0:4])[0]
result = []
pos = 4
while pos < len(data) and len(result) < original_size:
flag = data[pos]
pos += 1
if flag == 0: # Match
if pos + 2 >= len(data):
break
offset = struct.unpack('>H', data[pos:pos+2])[0]
length = data[pos + 2]
pos += 3
start = len(result) - offset
for i in range(length):
if start + i < len(result):
result.append(result[start + i])
else:
break
else: # Literal
if pos >= len(data):
break
result.append(data[pos])
pos += 1
return bytes(result[:original_size])
# ==================== LZW Compression ====================
class LZWCompression:
"""Lempel-Ziv-Welch compression"""
@staticmethod
def compress(data: bytes) -> bytes:
"""Compress data using LZW"""
if not data:
return b''
# Initialize dictionary with single byte entries
dictionary = {bytes([i]): i for i in range(256)}
next_code = 256
max_code = 65535 # 16-bit codes
result = []
current = b''
for byte in data:
new_seq = current + bytes([byte])
if new_seq in dictionary:
current = new_seq
else:
# Output code for current sequence
result.append(dictionary[current])
# Add new sequence to dictionary if not full
if next_code <= max_code:
dictionary[new_seq] = next_code
next_code += 1
current = bytes([byte])
# Output final code
if current:
result.append(dictionary[current])
# Pack codes as 16-bit values
encoded = struct.pack('>' + 'H' * len(result), *result)
# Add header
header = struct.pack('>I', len(data))
return header + encoded
@staticmethod
def decompress(data: bytes) -> bytes:
"""Decompress LZW encoded data"""
if not data or len(data) < 4:
return b''
original_size = struct.unpack('>I', data[0:4])[0]
# Initialize dictionary
dictionary = {i: bytes([i]) for i in range(256)}
next_code = 256
# Unpack 16-bit codes
code_data = data[4:]
if len(code_data) % 2 != 0:
code_data = code_data[:-1]
codes = struct.unpack('>' + 'H' * (len(code_data) // 2), code_data)
if not codes:
return b''
result = bytearray(dictionary[codes[0]])
prev_seq = dictionary[codes[0]]
for code in codes[1:]:
if code in dictionary:
current_seq = dictionary[code]
elif code == next_code:
# Special case: code not yet in dictionary
current_seq = prev_seq + bytes([prev_seq[0]])
else:
# Invalid code
continue
result.extend(current_seq)
# Add new entry to dictionary
if next_code < 65536:
dictionary[next_code] = prev_seq + bytes([current_seq[0]])
next_code += 1
prev_seq = current_seq
return bytes(result[:original_size])
# ==================== Main Application ====================
class CompressionUtility:
"""Main application class"""
ALGORITHMS = {
'Huffman': HuffmanCompression,
'RLE': RLECompression,
'LZ77': LZ77Compression,
'LZW': LZWCompression
}
def __init__(self, root):
self.root = root
self.root.title("Data Compression Utility")
self.root.geometry("900x750")
self.root.configure(bg='#1a1a2e')
# Style configuration
self.style = ttk.Style()
self.style.theme_use('clam')
# Configure styles
self.style.configure('TFrame', background='#1a1a2e')
self.style.configure('TLabel', background='#1a1a2e', foreground='#eee', font=('Segoe UI', 10))
self.style.configure('Title.TLabel', font=('Segoe UI', 18, 'bold'), foreground='#00d9ff')
self.style.configure('Header.TLabel', font=('Segoe UI', 12, 'bold'), foreground='#00d9ff')
self.style.configure('TButton', font=('Segoe UI', 10), padding=10)
self.style.configure('Action.TButton', font=('Segoe UI', 11, 'bold'))
self.style.configure('TRadiobutton', background='#1a1a2e', foreground='#eee', font=('Segoe UI', 10))
self.style.configure('TProgressbar', thickness=20)
# Variables
self.input_file = tk.StringVar()
self.output_file = tk.StringVar()
self.algorithm = tk.StringVar(value='Huffman')
self.mode = tk.StringVar(value='compress')
self.processing = False
self.create_widgets()
def create_widgets(self):
"""Create GUI widgets"""
# Main container
main_frame = ttk.Frame(self.root, padding=20)
main_frame.pack(fill=tk.BOTH, expand=True)
# Title
title_frame = ttk.Frame(main_frame)
title_frame.pack(fill=tk.X, pady=(0, 20))
ttk.Label(title_frame, text="🗜️ Data Compression Utility",
style='Title.TLabel').pack(side=tk.LEFT)
# Mode Selection
mode_frame = ttk.LabelFrame(main_frame, text=" Mode ", padding=15)
mode_frame.pack(fill=tk.X, pady=10)
mode_inner = ttk.Frame(mode_frame)
mode_inner.pack()
ttk.Radiobutton(mode_inner, text="📦 Compress", variable=self.mode,
value="compress", command=self.update_mode).pack(side=tk.LEFT, padx=20)
ttk.Radiobutton(mode_inner, text="📂 Decompress", variable=self.mode,
value="decompress", command=self.update_mode).pack(side=tk.LEFT, padx=20)
# Algorithm Selection
algo_frame = ttk.LabelFrame(main_frame, text=" Algorithm ", padding=15)
algo_frame.pack(fill=tk.X, pady=10)
algo_inner = ttk.Frame(algo_frame)
algo_inner.pack()
for algo in self.ALGORITHMS.keys():
ttk.Radiobutton(algo_inner, text=algo, variable=self.algorithm,
value=algo).pack(side=tk.LEFT, padx=15)
# Algorithm Info
self.algo_info = ttk.Label(algo_frame, text="", wraplength=800)
self.algo_info.pack(pady=(10, 0))
self.update_algo_info()
self.algorithm.trace('w', lambda *args: self.update_algo_info())
# File Selection
file_frame = ttk.LabelFrame(main_frame, text=" File Selection ", padding=15)
file_frame.pack(fill=tk.X, pady=10)
# Input file
input_row = ttk.Frame(file_frame)
input_row.pack(fill=tk.X, pady=5)
ttk.Label(input_row, text="Input:").pack(side=tk.LEFT, padx=(0, 10))
ttk.Entry(input_row, textvariable=self.input_file, width=50).pack(side=tk.LEFT, padx=5)
ttk.Button(input_row, text="Browse", command=self.browse_input).pack(side=tk.LEFT, padx=5)
# Output file
output_row = ttk.Frame(file_frame)
output_row.pack(fill=tk.X, pady=5)
ttk.Label(output_row, text="Output:").pack(side=tk.LEFT, padx=(0, 10))
ttk.Entry(output_row, textvariable=self.output_file, width=50).pack(side=tk.LEFT, padx=5)
ttk.Button(output_row, text="Browse", command=self.browse_output).pack(side=tk.LEFT, padx=5)
# Action Buttons
button_frame = ttk.Frame(main_frame)
button_frame.pack(fill=tk.X, pady=20)
self.compress_btn = ttk.Button(button_frame, text="▶ Compress",
command=self.run_compression, style='Action.TButton')
self.compress_btn.pack(pady=10)
# Progress bar
self.progress = ttk.Progressbar(main_frame, mode='indeterminate')
self.progress.pack(fill=tk.X, pady=10)
# Statistics Frame
stats_frame = ttk.LabelFrame(main_frame, text=" Statistics ", padding=15)
stats_frame.pack(fill=tk.X, pady=10)
stats_grid = ttk.Frame(stats_frame)
stats_grid.pack()
self.stats_labels = {}
stats_items = [
('original_size', 'Original Size:', 0, 0),
('compressed_size', 'Compressed Size:', 0, 2),
('ratio', 'Compression Ratio:', 1, 0),
('time', 'Processing Time:', 1, 2)
]
for key, label, row, col in stats_items:
ttk.Label(stats_grid, text=label, style='Header.TLabel').grid(
row=row, column=col*2, padx=10, pady=5, sticky='e')
self.stats_labels[key] = ttk.Label(stats_grid, text="-", width=20)
self.stats_labels[key].grid(row=row, column=col*2+1, padx=10, pady=5, sticky='w')
# Log Output
log_frame = ttk.LabelFrame(main_frame, text=" Log ", padding=10)
log_frame.pack(fill=tk.BOTH, expand=True, pady=10)
self.log_text = scrolledtext.ScrolledText(log_frame, height=8,
bg='#0f0f1a', fg='#00ff88',
font=('Consolas', 9))
self.log_text.pack(fill=tk.BOTH, expand=True)
# Compare All Button
compare_frame = ttk.Frame(main_frame)
compare_frame.pack(fill=tk.X, pady=10)
ttk.Button(compare_frame, text="📊 Compare All Algorithms",
command=self.compare_all).pack()
def update_algo_info(self):
"""Update algorithm information text"""
info = {
'Huffman': 'Huffman Coding: Uses variable-length codes based on character frequency. '
'Best for text with uneven character distribution. Lossless.',
'RLE': 'Run-Length Encoding: Replaces consecutive identical bytes with count+byte. '
'Best for data with many repeated sequences. Simple and fast.',
'LZ77': 'LZ77: Sliding window compression that replaces repeated patterns with references. '
'Good balance of speed and compression. Used in ZIP, gzip.',
'LZW': 'LZW: Dictionary-based compression that builds codes for common patterns. '
'Used in GIF images and UNIX compress. Good for text.'
}
self.algo_info.config(text=info.get(self.algorithm.get(), ''))
def update_mode(self):
"""Update UI based on mode"""
if self.mode.get() == 'compress':
self.compress_btn.config(text="▶ Compress")
else:
self.compress_btn.config(text="▶ Decompress")
def browse_input(self):
"""Browse for input file"""
filename = filedialog.askopenfilename(title="Select Input File")
if filename:
self.input_file.set(filename)
# Auto-generate output filename
if self.mode.get() == 'compress':
self.output_file.set(filename + '.compressed')
else:
if filename.endswith('.compressed'):
self.output_file.set(filename[:-11])
else:
self.output_file.set(filename + '.decompressed')
def browse_output(self):
"""Browse for output file"""
filename = filedialog.asksaveasfilename(title="Select Output File")
if filename:
self.output_file.set(filename)
def log(self, message):
"""Add message to log"""
timestamp = time.strftime("%H:%M:%S")
self.log_text.insert(tk.END, f"[{timestamp}] {message}\n")
self.log_text.see(tk.END)
def update_stats(self, original_size, compressed_size, elapsed_time):
"""Update statistics display"""
self.stats_labels['original_size'].config(
text=self.format_size(original_size))
self.stats_labels['compressed_size'].config(
text=self.format_size(compressed_size))
if original_size > 0:
ratio = (1 - compressed_size / original_size) * 100
self.stats_labels['ratio'].config(text=f"{ratio:.2f}%")
else:
self.stats_labels['ratio'].config(text="-")
self.stats_labels['time'].config(text=f"{elapsed_time:.3f} seconds")
@staticmethod
def format_size(size):
"""Format size in human-readable format"""
for unit in ['B', 'KB', 'MB', 'GB']:
if size < 1024:
return f"{size:.2f} {unit}"
size /= 1024
return f"{size:.2f} TB"
def run_compression(self):
"""Run compression/decompression in separate thread"""
if self.processing:
return
input_path = self.input_file.get()
output_path = self.output_file.get()
if not input_path or not output_path:
messagebox.showerror("Error", "Please select input and output files")
return
if not os.path.exists(input_path):
messagebox.showerror("Error", "Input file does not exist")
return
self.processing = True
self.compress_btn.config(state='disabled')
self.progress.start()
thread = threading.Thread(target=self._process_file,
args=(input_path, output_path))
thread.daemon = True
thread.start()
def _process_file(self, input_path, output_path):
"""Process file (compress or decompress)"""
try:
algo_name = self.algorithm.get()
algorithm = self.ALGORITHMS[algo_name]
mode = self.mode.get()
self.log(f"Reading input file: {input_path}")
with open(input_path, 'rb') as f:
data = f.read()
original_size = len(data)
start_time = time.time()
if mode == 'compress':
self.log(f"Compressing with {algo_name}...")
result = algorithm.compress(data)
else:
self.log(f"Decompressing with {algo_name}...")
result = algorithm.decompress(data)
elapsed_time = time.time() - start_time
compressed_size = len(result)
self.log(f"Writing output file: {output_path}")
with open(output_path, 'wb') as f:
f.write(result)
self.log(f"✓ {'Compression' if mode == 'compress' else 'Decompression'} complete!")
# Update stats in main thread
self.root.after(0, lambda: self.update_stats(
original_size, compressed_size, elapsed_time))
self.root.after(0, lambda: messagebox.showinfo(
"Success",
f"{'Compression' if mode == 'compress' else 'Decompression'} completed successfully!\n"
f"Output: {output_path}"
))
except Exception as e:
self.log(f"✗ Error: {str(e)}")
self.root.after(0, lambda: messagebox.showerror("Error", str(e)))
finally:
self.processing = False
self.root.after(0, lambda: self.compress_btn.config(state='normal'))
self.root.after(0, lambda: self.progress.stop())
def compare_all(self):
"""Compare all algorithms on selected file"""
input_path = self.input_file.get()
if not input_path:
# Generate sample data if no file selected
self.log("No file selected. Generating sample data...")
sample_data = self.generate_sample_data()
# Create temporary file
temp_path = "temp_sample.bin"
with open(temp_path, 'wb') as f:
f.write(sample_data)
input_path = temp_path
elif not os.path.exists(input_path):
messagebox.showerror("Error", "Input file does not exist")
return
self.log("=" * 60)
self.log("Algorithm Comparison Results")
self.log("=" * 60)
try:
with open(input_path, 'rb') as f:
data = f.read()
original_size = len(data)
self.log(f"Original size: {self.format_size(original_size)}")
self.log("-" * 60)
results = []
for algo_name, algorithm in self.ALGORITHMS.items():
try:
start_time = time.time()
compressed = algorithm.compress(data)
elapsed = time.time() - start_time
compressed_size = len(compressed)
ratio = (1 - compressed_size / original_size) * 100 if original_size > 0 else 0
# Verify by decompressing
decompressed = algorithm.decompress(compressed)
valid = decompressed == data
result_str = (f"{algo_name:10} | Size: {self.format_size(compressed_size):12} | "
f"Ratio: {ratio:6.2f}% | Time: {elapsed:.4f}s | Valid: {'✓' if valid else '✗'}")
self.log(result_str)
results.append({
'name': algo_name,
'size': compressed_size,
'ratio': ratio,
'time': elapsed,
'valid': valid
})
except Exception as e:
self.log(f"{algo_name:10} | Error: {str(e)}")
self.log("-" * 60)
# Find best algorithm
if results:
best_ratio = max(results, key=lambda x: x['ratio'] if x['valid'] else -100)
best_speed = min(results, key=lambda x: x['time'] if x['valid'] else float('inf'))
self.log(f"Best compression: {best_ratio['name']} ({best_ratio['ratio']:.2f}%)")
self.log(f"Fastest: {best_speed['name']} ({best_speed['time']:.4f}s)")
except Exception as e:
self.log(f"Error during comparison: {str(e)}")
finally:
# Clean up temp file if created
if input_path == "temp_sample.bin" and os.path.exists(input_path):
os.remove(input_path)
@staticmethod
def generate_sample_data():
"""Generate sample data for testing"""
import random
data = bytearray()
# Some repeated patterns (good for LZ77/LZW)
pattern = b"The quick brown fox jumps over the lazy dog. "
data.extend(pattern * 50)
# Some runs of same byte (good for RLE)
data.extend(b'A' * 100)
data.extend(b'B' * 50)
data.extend(b'C' * 75)
# Some text with varying frequency (good for Huffman)
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
text += "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "
data.extend(text.encode() * 30)
# Some random data
random.seed(42)
data.extend(bytes([random.randint(0, 255) for _ in range(500)]))
# More patterns
data.extend(pattern * 30)
data.extend(b'X' * 200)
return bytes(data)
def main():
"""Main entry point"""
root = tk.Tk()
# Set window icon (optional, won't fail if not available)
try:
root.iconbitmap('')
except:
pass
app = CompressionUtility(root)
root.mainloop()
if __name__ == "__main__":
main()
Features
Compression Algorithms Supported:
Algorithm
Description
Best For
Huffman
Variable-length codes based on frequency
Text with uneven character distribution
RLE
Run-Length Encoding
Data with repeated sequences
LZ77
Sliding window dictionary compression
General purpose, balanced speed/ratio
LZW
Dictionary-based with code table
Text files, used in GIF/UNIX compress
GUI Features:
📦 Compress/Decompress modes
📁 File browser for input/output selection
📊 Real-time statistics (size, ratio, time)
📝 Activity log with timestamps
🔄 Compare All feature to test all algorithms
🎨 Modern dark theme interface
Installation & Running
bash
# No additional packages required! Uses only Python standard library
python compression_utility.py
Usage
Select Mode: Choose Compress or Decompress
Select Algorithm: Pick from Huffman, RLE, LZ77, or LZW
Choose Files: Browse for input file (output auto-generated)
Run: Click Compress/Decompress button
Compare: Click "Compare All Algorithms" to see which works best for your data