fastrunner's picture
Upload folder using huggingface_hub
8982ff7 verified
Raw History Blame Contribute Delete
11.1 kB
"""
🧠 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()