TuringsSolutions/Fibonacci-Compressor
0
1import streamlit as st2import os3import tempfile4import numpy as np5from PIL import Image6from flc_core import flc_encode_file, flc_decode_file, cosine_similarity_bytes7 8st.set_page_config(page_title="FLC v1.3 | How it Works", layout="wide")9 10# Styling for a "Scientific Laboratory" look11st.markdown("""12 <style>13 .reportview-container { background: #0e1117; }14 .main { color: #e0e0e0; }15 h1, h2, h3 { color: #f1c40f !important; }16 .stAlert { background-color: #1a1c24; border: 1px solid #f1c40f; }17 </style>18 """, unsafe_allow_html=True)19 20st.title("๐ Fibonacci Lattice Compression (FLC)")21st.markdown("""22 **FLC v1.3** is a bio-inspired data compression architecture. Unlike standard ZIP or JPEG formats, 23 FLC uses the **Golden Ratio ($\Phi$)** to decide which parts of your data are "essential" and which are "noise."24""")25 26# --- PILLAR 1: THE EXPLAINER ---27with st.expander("๐ Step-by-Step: How does the 'Secret Sauce' work?"):28 col1, col2, col3 = st.columns(3)29 30 with col1:31 st.markdown("### 1. Spectral Projection")32 st.write("""33 We treat your data like a sound wave. Using a **DCT (Discrete Cosine Transform)**, 34 we project the bits into frequency space. 35 * **Low Frequencies:** The "skeleton" of your data.36 * **High Frequencies:** The "dust" and fine details.37 """)38 39 with col2:40 st.markdown("### 2. The Golden Filter")41 st.write("""42 Instead of treating all frequencies equally, FLC uses **Fibonacci Bands**. 43 We compress the 'dust' using steps based on the **Golden Ratio ($\Phi \approx 1.618$)**. 44 As the frequency increases, the compression gets exponentially more aggressive.45 """)46 47 with col3:48 with st.container():49 st.markdown("### 3. Fibonacci Coding")50 st.write("""51 Standard computers use 8-bit bytes. FLC uses **Fibonacci Binary**. 52 It's a "universal code" that uses the sum of Fibonacci numbers to represent values, 53 making the compressed stream incredibly resilient and dense.54 """)55 56st.divider()57 58# --- PILLAR 2: THE INTERACTIVE DEMO ---59st.header("๐งช Test the Horizon")60with st.sidebar:61 st.header("๐๏ธ Architecture Params")62 st.info("Adjusting these changes how the 'Secret Sauce' math is applied.")63 64 quality_map = {65 "High Compression (Lossy)": {"bands": 6, "step": 0.08, "desc": "Aggressive $\Phi$-scaling."},66 "Balanced": {"bands": 12, "step": 0.005, "desc": "The Golden Mean of fidelity."},67 "Near-Lossless": {"bands": 24, "step": 0.0001, "desc": "Full spectral recovery."}68 }69 70 tier = st.radio("Fidelity Tier", list(quality_map.keys()), index=1)71 st.caption(quality_map[tier]["desc"])72 73 st.subheader("Visual Overlays")74 show_spiral = st.checkbox("Fibonacci Spiral Outlines", value=True)75 show_ring = st.checkbox("Event Horizon Ring", value=True)76 77uploaded_file = st.file_uploader("Upload a file (Image, Text, or Binary)", type=["bin", "png", "jpg", "txt"])78 79if uploaded_file is not None:80 with tempfile.TemporaryDirectory() as tmpdir:81 in_path = os.path.join(tmpdir, "input.bin")82 out_flc = os.path.join(tmpdir, "output.flc")83 out_gif = os.path.join(tmpdir, "unzip.gif")84 recovered_path = os.path.join(tmpdir, "recovered.bin")85 86 with open(in_path, "wb") as f:87 f.write(uploaded_file.getbuffer())88 89 if st.button("RUN HOLOGRAPHIC RECONSTRUCTION"):90 with st.status("Initializing Fibonacci Manifolds...", expanded=True) as status:91 st.write("Transforming data to Frequency Space...")92 enc = flc_encode_file(93 in_path, out_flc, unzip_gif=out_gif,94 n_bands=quality_map[tier]["bands"], 95 base_step=quality_map[tier]["step"]96 )97 98 st.write("Applying $\Phi$-scaled quantization...")99 dec = flc_decode_file(out_flc, recovered_path)100 101 st.write("Generating Holographic Unzip visualization...")102 status.update(label="Reconstruction Complete!", state="complete", expanded=False)103 104 # Results Section105 st.subheader("๐ Compression Performance")106 c1, c2, c3, c4 = st.columns(4)107 c1.metric("Original Size", f"{enc['n_bytes']} B")108 c2.metric("Compressed Size", f"{enc['payload_len']} B")109 c3.metric("Ratio", f"{enc['ratio']:.2%}")110 111 # Calculate Similarity112 orig_data = open(in_path, "rb").read()113 reco_data = open(recovered_path, "rb").read()114 fidelity = cosine_similarity_bytes(orig_data, reco_data)115 c4.metric("Data Fidelity", f"{fidelity*100:.2f}%")116 117 st.divider()118 119 # Visualization120 st.header("๐๏ธ The Unzip Sequence")121 st.markdown("""122 This animation shows the **Progressive Reconstruction**. 123 The 'Hologram' on the left shows the frequency data being added band-by-band. 124 The 'Spiral' on the right shows the bits filling the Fibonacci tiles in real-time.125 """)126 127 if os.path.exists(out_gif):128 st.image(out_gif, use_container_width=True)129 130 st.info("๐ก Notice how the general shape appears first, and the fine details (noise) appear last. This is the hallmark of Spectral Compression.")131 132 with open(out_flc, "rb") as f:133 st.download_button("๐ฅ Download Encoded .FLC File", f, file_name="demo.flc")134 135else:136 st.warning("Please upload a file to visualize the Fibonacci transformation.")