File size: 11,056 Bytes
8982ff7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""
🧠 Entroly Context Compression β€” Hugging Face Space
=====================================================
Interactive demo: compress LLM context by 70-95% while preserving accuracy.
Zero API keys β€” everything runs locally in <10ms.
"""

import time
import hashlib
import gradio as gr

try:
    from entroly import compress, compress_messages
    ENTROLY_AVAILABLE = True
except ImportError:
    ENTROLY_AVAILABLE = False


# ── Sample Data ──────────────────────────────────────────────────────────

SAMPLE_CODE = '''import os
import json
import logging
from pathlib import Path
from typing import Optional, Dict, List, Any
from dataclasses import dataclass, field

logger = logging.getLogger(__name__)

@dataclass
class DatabaseConfig:
    """Configuration for database connections."""
    host: str = "localhost"
    port: int = 5432
    database: str = "myapp"
    username: str = "admin"
    password: str = ""
    pool_size: int = 10
    max_overflow: int = 20
    pool_timeout: int = 30
    echo: bool = False

    def connection_string(self) -> str:
        """Generate a SQLAlchemy connection string."""
        return f"postgresql://{self.username}:{self.password}@{self.host}:{self.port}/{self.database}"

    def validate(self) -> List[str]:
        errors = []
        if not self.host:
            errors.append("Database host is required")
        if self.port < 1 or self.port > 65535:
            errors.append(f"Invalid port: {self.port}")
        if not self.database:
            errors.append("Database name is required")
        if self.pool_size < 1:
            errors.append("Pool size must be at least 1")
        if self.max_overflow < 0:
            errors.append("Max overflow cannot be negative")
        return errors


@dataclass
class CacheConfig:
    """Configuration for caching layer."""
    backend: str = "redis"
    host: str = "localhost"
    port: int = 6379
    ttl: int = 3600
    max_connections: int = 50
    key_prefix: str = "myapp:"
    serializer: str = "json"

    def validate(self) -> List[str]:
        errors = []
        if self.backend not in ("redis", "memcached", "local"):
            errors.append(f"Unknown cache backend: {self.backend}")
        if self.ttl < 0:
            errors.append("TTL cannot be negative")
        return errors


@dataclass
class AppConfig:
    """Main application configuration."""
    app_name: str = "MyApp"
    version: str = "1.0.0"
    debug: bool = False
    log_level: str = "INFO"
    secret_key: str = ""
    allowed_hosts: List[str] = field(default_factory=lambda: ["*"])
    database: DatabaseConfig = field(default_factory=DatabaseConfig)
    cache: CacheConfig = field(default_factory=CacheConfig)

    @classmethod
    def from_env(cls) -> "AppConfig":
        config = cls()
        config.app_name = os.getenv("APP_NAME", config.app_name)
        config.debug = os.getenv("DEBUG", "false").lower() == "true"
        config.log_level = os.getenv("LOG_LEVEL", config.log_level)
        config.database.host = os.getenv("DB_HOST", config.database.host)
        config.database.port = int(os.getenv("DB_PORT", str(config.database.port)))
        return config

    def validate(self) -> List[str]:
        errors = []
        if not self.secret_key and not self.debug:
            errors.append("SECRET_KEY is required in production")
        errors.extend(self.database.validate())
        errors.extend(self.cache.validate())
        return errors'''

SAMPLE_LOG = """2026-05-10 08:00:01 INFO  [main] Application starting up...
2026-05-10 08:00:01 INFO  [main] Loading configuration from /etc/myapp/config.json
2026-05-10 08:00:02 INFO  [db] Connecting to database at localhost:5432
2026-05-10 08:00:02 INFO  [db] Connection pool initialized (size=10)
2026-05-10 08:00:02 INFO  [cache] Connecting to Redis at localhost:6379
2026-05-10 08:00:03 INFO  [cache] Redis connection established
2026-05-10 08:00:03 INFO  [http] Starting HTTP server on 0.0.0.0:8080
2026-05-10 08:00:03 INFO  [http] Server ready to accept connections
2026-05-10 08:01:15 INFO  [http] GET /api/users 200 45ms
2026-05-10 08:01:16 INFO  [http] GET /api/users 200 12ms (cache hit)
2026-05-10 08:01:17 INFO  [http] GET /api/users 200 11ms (cache hit)
2026-05-10 08:01:20 INFO  [http] POST /api/users 201 89ms
2026-05-10 08:01:21 INFO  [cache] Cache invalidated: myapp:users:*
2026-05-10 08:01:25 INFO  [http] GET /api/users 200 42ms
2026-05-10 08:01:30 INFO  [http] GET /api/products 200 67ms
2026-05-10 08:01:31 INFO  [http] GET /api/products 200 9ms (cache hit)
2026-05-10 08:02:00 WARN  [db] Slow query detected: SELECT * FROM orders WHERE... (1523ms)
2026-05-10 08:02:15 ERROR [payment] Payment processing failed for order #4521
2026-05-10 08:02:15 ERROR [payment] Traceback: ConnectionRefusedError: payment-gateway:443
2026-05-10 08:02:16 INFO  [payment] Retrying payment for order #4521 (attempt 2/3)
2026-05-10 08:02:17 INFO  [payment] Payment successful for order #4521 on retry
2026-05-10 08:03:00 INFO  [health] Health check OK: db=up cache=up payment=up"""


SAMPLES = {
    "Python Code": SAMPLE_CODE,
    "Server Logs": SAMPLE_LOG,
}


# ── Core Functions ───────────────────────────────────────────────────────

def compress_content(content_type, custom_text, budget):
    if not ENTROLY_AVAILABLE:
        return "⚠️ entroly not installed", "", "", ""

    input_text = custom_text if content_type == "Custom" else SAMPLES.get(content_type, custom_text)
    if not input_text:
        return "No input provided", "", "", ""

    start = time.perf_counter()
    result = compress(input_text, budget=int(budget))
    elapsed_ms = (time.perf_counter() - start) * 1000

    orig_tokens = len(input_text) // 4
    comp_tokens = len(result) // 4
    savings = max(0, (1 - comp_tokens / max(orig_tokens, 1))) * 100

    stats = (
        f"πŸ“Š Original: {orig_tokens:,} tokens β†’ Compressed: {comp_tokens:,} tokens\n"
        f"πŸ’° Savings: {savings:.1f}%\n"
        f"⚑ Latency: {elapsed_ms:.1f}ms"
    )
    return result, stats


def run_benchmark():
    if not ENTROLY_AVAILABLE:
        return "⚠️ entroly not installed"

    budgets = [100, 250, 500, 1000, 2000, 5000]
    lines = ["Budget | Output Tokens | Savings % | Latency (ms)", "--- | --- | --- | ---"]
    for b in budgets:
        start = time.perf_counter()
        result = compress(SAMPLE_CODE, budget=b)
        elapsed = (time.perf_counter() - start) * 1000
        orig = len(SAMPLE_CODE) // 4
        comp = len(result) // 4
        savings = max(0, (1 - comp / max(orig, 1))) * 100
        lines.append(f"{b} | {comp} | {savings:.1f}% | {elapsed:.1f}ms")
    return "\n".join(lines)


def run_determinism_check():
    if not ENTROLY_AVAILABLE:
        return "⚠️ entroly not installed"

    hashes = []
    for _ in range(10):
        result = compress(SAMPLE_CODE, budget=500)
        h = hashlib.sha256(result.encode()).hexdigest()
        hashes.append(h)

    unique = set(hashes)
    if len(unique) == 1:
        return (
            f"βœ… PASSED β€” All 10 runs produced identical output.\n\n"
            f"SHA-256: {hashes[0]}\n\n"
            f"This proves Entroly's compression is fully deterministic β€” "
            f"no neural networks, no randomness, no GPU. Pure information-theoretic selection."
        )
    else:
        return f"❌ FAILED β€” {len(unique)} distinct outputs detected."


def load_sample(content_type):
    return SAMPLES.get(content_type, "")


# ── Gradio UI ────────────────────────────────────────────────────────────

with gr.Blocks(
    title="Entroly Context Compression",
    theme=gr.themes.Soft(primary_hue="purple"),
) as demo:
    gr.Markdown(
        "# 🧠 Entroly β€” Context Compression Demo\n"
        "**The first self-improving context engine for AI coding.**  \n"
        "Compress LLM context by **70–95%** while preserving accuracy. "
        "No API keys needed β€” everything runs locally in <10ms.\n\n"
        "πŸ“¦ [GitHub](https://github.com/juyterman1000/entroly) Β· "
        "πŸ“„ [PyPI](https://pypi.org/project/entroly/) Β· "
        "πŸ“œ Apache 2.0 License"
    )

    with gr.Tab("πŸ“„ Compress"):
        with gr.Row():
            content_type = gr.Dropdown(
                choices=["Python Code", "Server Logs", "Custom"],
                value="Python Code",
                label="Content Type",
            )
            budget = gr.Slider(
                minimum=50, maximum=5000, value=500, step=50, label="Token Budget"
            )

        input_text = gr.Textbox(
            label="Input",
            value=SAMPLE_CODE,
            lines=15,
            max_lines=30,
        )
        compress_btn = gr.Button("πŸš€ Compress", variant="primary")
        stats_out = gr.Textbox(label="Stats", lines=3, interactive=False)
        output_text = gr.Textbox(label="Compressed Output", lines=15, interactive=False)

        content_type.change(load_sample, inputs=content_type, outputs=input_text)
        compress_btn.click(
            compress_content,
            inputs=[content_type, input_text, budget],
            outputs=[output_text, stats_out],
        )

    with gr.Tab("πŸ“Š Benchmark"):
        gr.Markdown(
            "Run compression at 6 budget levels on the sample Python code. "
            "Verify savings and latency yourself."
        )
        bench_btn = gr.Button("▢️ Run Benchmark", variant="primary")
        bench_out = gr.Markdown()
        bench_btn.click(run_benchmark, outputs=bench_out)

        gr.Markdown(
            "### Published Benchmark Results (gpt-4o-mini, Wilson 95% CIs)\n\n"
            "| Benchmark | Accuracy Retention | Token Savings |\n"
            "| --- | --- | --- |\n"
            "| NeedleInAHaystack | 100% | 99.5% |\n"
            "| LongBench (HotpotQA) | 106.2% | 85.3% |\n"
            "| Berkeley Function Calling | 100% | 79.3% |\n"
            "| SQuAD 2.0 | 97.4% | 39.3% |\n\n"
            "> All CIs overlap β€” accuracy is statistically indistinguishable from baseline."
        )

    with gr.Tab("πŸ”¬ Determinism Proof"):
        gr.Markdown(
            "Entroly is **fully deterministic**: same input β†’ identical output, every time. "
            "Click below to run 10 compressions and verify the SHA-256 hashes are bit-identical.\n\n"
            "This is running on **Hugging Face infrastructure** β€” not our servers. "
            "You can trust these results."
        )
        determ_btn = gr.Button("πŸ”’ Run Determinism Check", variant="primary")
        determ_out = gr.Textbox(label="Result", lines=5, interactive=False)
        determ_btn.click(run_determinism_check, outputs=determ_out)


if __name__ == "__main__":
    demo.launch()