
#!/usr/bin/env python3
"""
ANALOG FRACTAL WORKBENCH 2.1
============================

Whole-image fractal synthesis using geometric RC ladder kernels.

Properties:
    - No fixed image blocks.
    - No patch-based reconstruction.
    - Geometric series-R / shunt-C ladder.
    - Continuous radial spatial-frequency response.
    - Sparse spatial excitation.
    - Shared RGB impulse positions.
    - Progressive whole-image residual fitting.
    - Actual compressed JSON model byte count.
    - Live local dashboard.
    - Periodic model checkpointing.

Dependencies:
    py -m pip install numpy pillow

Run:
    py analog_fractal_workbench1.py photograph.jpg --stages 16 --bins 192 --iterations 100

Dashboard:
    http://127.0.0.1:8766
"""

from __future__ import annotations

import argparse
import base64
import io
import json
import math
import threading
import time
import zlib

from fractions import Fraction
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

import numpy as np
from PIL import Image


VERSION = "ANALOG-FRACTAL-2.1"

STATE = {
    "status": "starting",
    "message": "Initializing",
    "stage": 0,
    "stages": 0,
    "mse": None,
    "model_bytes": 0,
    "elapsed": 0.0,
    "history": [],
    "original": None,
    "reconstruction": None,
    "residual": None,
    "spectrum": None,
}


# ============================================================
# IMAGE
# ============================================================

def load_image(filename, max_side):
    image = Image.open(filename).convert("RGB")
    original_size = image.size

    scale = min(1.0, max_side / max(image.size))

    if scale < 1.0:
        image = image.resize(
            (
                max(1, round(image.width * scale)),
                max(1, round(image.height * scale)),
            ),
            Image.Resampling.LANCZOS,
        )

    return (
        np.asarray(image, dtype=np.float64) / 255.0,
        original_size,
    )


def mse(a, b):
    return float(np.mean((a - b) ** 2))


def display_image(array, max_side=640):
    array = np.asarray(array, dtype=np.float64)

    if array.ndim == 2:
        array = np.repeat(array[:, :, None], 3, axis=2)

    array = np.clip(array, 0.0, 1.0)

    image = Image.fromarray((array * 255).astype(np.uint8))

    if max(image.size) > max_side:
        scale = max_side / max(image.size)
        image = image.resize(
            (
                max(1, int(image.width * scale)),
                max(1, int(image.height * scale)),
            ),
            Image.Resampling.LANCZOS,
        )

    buf = io.BytesIO()
    image.save(buf, format="JPEG", quality=80)

    return "data:image/jpeg;base64," + base64.b64encode(
        buf.getvalue()
    ).decode("ascii")


def normalized_display(array):
    array = np.asarray(array, dtype=np.float64)
    low = float(np.min(array))
    high = float(np.max(array))

    if high - low < 1e-14:
        return np.zeros_like(array)

    return (array - low) / (high - low)


# ============================================================
# EXACT RATIO IDENTITIES
# ============================================================

def exact_ratios():
    values = [
        "1.125",
        "1.2",
        "1.25",
        "1.3333333333333333",
        "1.5",
        "1.6666666666666667",
        "1.75",
        "2",
        "2.25",
        "2.5",
        "3",
    ]

    return sorted(set(Fraction(x) for x in values))


def candidate_families():
    ratios = exact_ratios()
    result = []

    for rho in ratios:
        for gamma in ratios:
            if rho <= 1 or gamma <= 1:
                continue

            for n in (3, 4, 5, 6, 8, 10, 12):
                rf = float(rho)
                gf = float(gamma)

                result.append({
                    "rho_num": rho.numerator,
                    "rho_den": rho.denominator,
                    "gamma_num": gamma.numerator,
                    "gamma_den": gamma.denominator,
                    "rho": rf,
                    "gamma": gf,
                    "n": n,
                    "alpha": math.log(rf) / math.log(rf * gf),
                })

    return result


# ============================================================
# GEOMETRIC RC LADDER
# ============================================================

def ladder_impedance(frequencies, rho, gamma, n):
    """
    Geometric series-R / shunt-C ladder.

    Z_k(s) = R_k + 1 / (s*C_k + 1/Z_(k+1))

    R_k = rho**k
    C_k = gamma**k
    """
    s = 1j * np.asarray(frequencies, dtype=np.float64)
    s = np.where(np.abs(s) < 1e-12, 1e-12 + 0j, s)

    k = n - 1

    z = rho ** k + 1.0 / (s * gamma ** k)

    for k in range(n - 2, -1, -1):
        resistance = rho ** k
        capacitance = gamma ** k

        z = resistance + 1.0 / (
            s * capacitance + 1.0 / z
        )

    return z


def ladder_response(radius, family):
    rho = family["rho"]
    gamma = family["gamma"]
    n = family["n"]

    f = np.maximum(np.asarray(radius), 1e-5)

    z = ladder_impedance(f, rho, gamma, n)

    reference_frequency = float(np.median(f))

    zref = ladder_impedance(
        np.array([reference_frequency]),
        rho,
        gamma,
        n,
    )[0]

    magnitude = np.abs(z / zref)
    magnitude = np.maximum(magnitude, 1e-12)

    # Normalize the radial response without changing its shape.
    magnitude /= np.median(magnitude)

    return magnitude


# ============================================================
# SPATIAL FREQUENCY GRID
# ============================================================

def frequency_grid(height, width):
    fy = np.fft.fftfreq(height)
    fx = np.fft.rfftfreq(width)

    yy, xx = np.meshgrid(fy, fx, indexing="ij")

    return np.sqrt(xx * xx + yy * yy)


def radial_bin_data(radius, bins):
    maximum = float(np.max(radius))

    edges = np.linspace(0.0, maximum + 1e-12, bins + 1)

    index = np.digitize(radius.ravel(), edges) - 1
    index = np.clip(index, 0, bins - 1)

    counts = np.bincount(
        index,
        minlength=bins,
    ).astype(np.float64)

    centers = (edges[:-1] + edges[1:]) * 0.5

    return centers, index, counts


def radial_average(values, index, counts, bins):
    sums = np.bincount(
        index,
        weights=np.asarray(values).ravel(),
        minlength=bins,
    )

    return sums / np.maximum(counts, 1.0)


# ============================================================
# SPECTRAL CANDIDATE DISCOVERY
# ============================================================

def family_spectral_error(
    family,
    target_power,
    radius,
    index,
    counts,
    bins,
):
    response = ladder_response(radius, family)
    predicted = response * response

    predicted_radial = radial_average(
        predicted,
        index,
        counts,
        bins,
    )

    valid = (
        (target_power > 1e-12)
        & (predicted_radial > 1e-12)
    )

    if np.count_nonzero(valid) < 8:
        return float("inf")

    a = np.log(target_power[valid])
    b = np.log(predicted_radial[valid])

    # Remove arbitrary gain.
    b += np.mean(a - b)

    return float(np.mean((a - b) ** 2))


def discover_best_family(residual, families, bins):
    height, width, channels = residual.shape

    radius = frequency_grid(height, width)

    centers, index, counts = radial_bin_data(
        radius,
        bins,
    )

    spectrum = np.fft.rfft2(
        residual,
        axes=(0, 1),
    )

    power = np.mean(
        np.abs(spectrum) ** 2,
        axis=2,
    )

    target_power = radial_average(
        power,
        index,
        counts,
        bins,
    )

    best = None
    best_error = float("inf")

    for i, family in enumerate(families):
        error = family_spectral_error(
            family,
            target_power,
            radius,
            index,
            counts,
            bins,
        )

        if error < best_error:
            best_error = error
            best = family

        if i % 16 == 0:
            STATE["message"] = (
                f"Candidate search {i + 1}/{len(families)}"
            )

    return best, best_error, centers, target_power


# ============================================================
# GENERATOR KERNEL
# ============================================================

def make_generator(family, shape):
    height, width, _ = shape

    radius = frequency_grid(height, width)

    response = ladder_response(radius, family)

    # The DC component is not used as an impulse-shape component.
    response[0, 0] = 0.0

    kernel = np.fft.irfft2(
        response,
        s=(height, width),
    )

    norm = float(np.sqrt(np.sum(kernel * kernel)))

    if norm < 1e-14:
        raise ValueError("Degenerate generator kernel")

    kernel /= norm

    # Recalculate the response from the normalized kernel.
    # This guarantees that synthesis and stored coefficients
    # refer to exactly the same spatial kernel.
    response = np.fft.rfft2(kernel)

    # A real, even radial kernel should have negligible imaginary
    # component. Retain the real component for stable filtering.
    response = response.real

    return response, kernel


# ============================================================
# SPARSE WHOLE-IMAGE MATCHING PURSUIT
# ============================================================

def sparse_impulse_fit(
    residual,
    kernel,
    max_atoms=64,
    threshold=0.012,
):
    """
    Match translated copies of a continuous RC-ladder kernel
    against the entire RGB residual.

    The kernel is 2D.
    The image residual is H x W x 3.

    No image blocks are formed.
    """

    height, width, channels = residual.shape

    kernel = np.asarray(kernel, dtype=np.float64)

    if kernel.shape != (height, width):
        raise ValueError(
            f"Kernel shape {kernel.shape} does not match "
            f"image shape {(height, width)}"
        )

    kernel_energy = float(np.sum(kernel * kernel))

    if kernel_energy < 1e-16:
        return [], np.zeros_like(residual)

    kernel_fft = np.fft.rfft2(kernel)

    current = residual.copy()
    generated = np.zeros_like(residual)

    atoms = []

    for atom_index in range(max_atoms):

        current_fft = np.fft.rfft2(
            current,
            axes=(0, 1),
        )

        correlation = np.fft.irfft2(
            current_fft * np.conj(kernel_fft)[:, :, None],
            s=(height, width),
            axes=(0, 1),
        )

        score = np.sum(
            correlation * correlation,
            axis=2,
        )

        y, x = np.unravel_index(
            int(np.argmax(score)),
            score.shape,
        )

        vector = correlation[y, x, :] / kernel_energy

        improvement = float(
            np.sum(correlation[y, x, :] ** 2)
            / kernel_energy
        )

        if not np.isfinite(improvement):
            break

        if improvement < threshold:
            break

        shifted_kernel = np.roll(
            np.roll(kernel, int(y), axis=0),
            int(x),
            axis=1,
        )

        # Correct RGB broadcast:
        # H x W x 1 multiplied by 1 x 1 x 3 -> H x W x 3.
        contribution = (
            shifted_kernel[:, :, None]
            * vector[None, None, :]
        )

        current -= contribution
        generated += contribution

        atoms.append({
            "y": int(y),
            "x": int(x),
            "rgb": [
                float(vector[0]),
                float(vector[1]),
                float(vector[2]),
            ],
        })

        if atom_index % 8 == 0:
            STATE["message"] = (
                f"Matching pursuit atom "
                f"{atom_index + 1}/{max_atoms}"
            )

    return atoms, generated


# ============================================================
# MODEL RENDERING
# ============================================================

def render_atoms(atoms, kernel, shape):
    height, width, channels = shape

    result = np.zeros(shape, dtype=np.float64)

    for atom in atoms:
        y = int(atom["y"])
        x = int(atom["x"])

        vector = np.asarray(
            atom["rgb"],
            dtype=np.float64,
        )

        shifted_kernel = np.roll(
            np.roll(kernel, y, axis=0),
            x,
            axis=1,
        )

        result += (
            shifted_kernel[:, :, None]
            * vector[None, None, :]
        )

    return result


# ============================================================
# MODEL SERIALIZATION
# ============================================================

def save_model(model, filename):
    raw = json.dumps(
        model,
        separators=(",", ":"),
        ensure_ascii=False,
    ).encode("utf-8")

    compressed = zlib.compress(raw, level=9)

    with open(filename, "wb") as f:
        f.write(compressed)

    return len(compressed)


# ============================================================
# DASHBOARD
# ============================================================

HTML = r"""
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Analog Fractal Workbench</title>
<style>
body {
    margin: 0;
    padding: 22px;
    background: #101318;
    color: #e8edf4;
    font-family: Segoe UI, Arial, sans-serif;
}
h1 { font-size: 22px; margin: 0 0 5px; }
small { color: #98a5b5; }
.status { margin: 16px 0; color: #b8c9da; }
.grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 14px;
}
.panel {
    background: #1a2029;
    border: 1px solid #303947;
    border-radius: 8px;
    padding: 12px;
    min-width: 0;
}
.panel h2 {
    font-size: 14px;
    font-weight: 600;
    margin: 0 0 10px;
}
img {
    width: 100%;
    display: block;
    background: #080a0d;
    min-height: 120px;
    object-fit: contain;
}
.metrics {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
    margin: 14px 0;
}
.metric {
    background: #1a2029;
    border: 1px solid #303947;
    border-radius: 7px;
    padding: 12px;
}
.metric b {
    display: block;
    font-size: 19px;
    margin-top: 5px;
}
.metric span { color: #9aa9ba; font-size: 11px; }
table { width: 100%; border-collapse: collapse; margin-top: 14px; }
td, th {
    text-align: left;
    padding: 7px;
    border-bottom: 1px solid #303947;
    font-size: 12px;
}
th { color: #9aa9ba; }
@media(max-width: 800px) {
    .grid { grid-template-columns: 1fr; }
    .metrics { grid-template-columns: repeat(2, 1fr); }
}
</style>
</head>
<body>
<h1>Analog Fractal Workbench</h1>
<small>Geometric RC ladder · continuous radial synthesis · sparse excitation</small>
<div class="status" id="status">Connecting...</div>

<div class="metrics">
 <div class="metric"><span>Stage</span><b id="stage">0</b></div>
 <div class="metric"><span>Whole-image MSE</span><b id="mse">—</b></div>
 <div class="metric"><span>Model bytes</span><b id="bytes">—</b></div>
 <div class="metric"><span>Elapsed</span><b id="elapsed">—</b></div>
</div>

<div class="grid">
 <div class="panel"><h2>Original</h2><img id="original"></div>
 <div class="panel"><h2>Analog reconstruction</h2><img id="reconstruction"></div>
 <div class="panel"><h2>Continuous residual field</h2><img id="residual"></div>
 <div class="panel"><h2>Radial ladder kernel</h2><img id="spectrum"></div>
</div>

<div class="panel" style="margin-top:14px">
<h2>Generator history</h2>
<table>
<thead><tr>
<th>Stage</th><th>rho</th><th>gamma</th><th>n</th>
<th>alpha</th><th>atoms</th><th>MSE</th><th>spectral error</th>
</tr></thead>
<tbody id="history"></tbody>
</table>
</div>

<script>
async function refresh() {
    try {
        const r = await fetch('/state');
        const s = await r.json();

        document.getElementById('status').textContent =
            s.message + ' · ' + s.status;

        document.getElementById('stage').textContent =
            s.stage + '/' + s.stages;

        document.getElementById('mse').textContent =
            s.mse === null ? '—' : Number(s.mse).toFixed(6);

        document.getElementById('bytes').textContent =
            s.model_bytes ?? '—';

        document.getElementById('elapsed').textContent =
            s.elapsed ? s.elapsed.toFixed(1) + 's' : '—';

        for (const key of [
            'original', 'reconstruction', 'residual', 'spectrum'
        ]) {
            if (s[key]) {
                const el = document.getElementById(key);
                if (el.src !== s[key]) el.src = s[key];
            }
        }

        document.getElementById('history').innerHTML =
            s.history.map(h => `<tr>
                <td>${h.stage}</td>
                <td>${h.rho.toFixed(5)}</td>
                <td>${h.gamma.toFixed(5)}</td>
                <td>${h.n}</td>
                <td>${h.alpha.toFixed(4)}</td>
                <td>${h.atoms}</td>
                <td>${h.mse.toFixed(6)}</td>
                <td>${h.spectral_error.toExponential(3)}</td>
            </tr>`).join('');
    } catch(e) {
        document.getElementById('status').textContent =
            'Dashboard connection error: ' + e;
    }
}
setInterval(refresh, 1000);
refresh();
</script>
</body>
</html>
"""


def start_dashboard(port):
    class Handler(BaseHTTPRequestHandler):

        def do_GET(self):
            if self.path == "/":
                data = HTML.encode("utf-8")

                self.send_response(200)
                self.send_header(
                    "Content-Type",
                    "text/html; charset=utf-8",
                )
                self.send_header(
                    "Content-Length",
                    str(len(data)),
                )
                self.end_headers()
                self.wfile.write(data)
                return

            if self.path == "/state":
                data = json.dumps(STATE).encode("utf-8")

                self.send_response(200)
                self.send_header(
                    "Content-Type",
                    "application/json",
                )
                self.send_header(
                    "Content-Length",
                    str(len(data)),
                )
                self.end_headers()
                self.wfile.write(data)
                return

            self.send_error(404)

        def log_message(self, *args):
            pass

    server = ThreadingHTTPServer(
        ("127.0.0.1", port),
        Handler,
    )

    thread = threading.Thread(
        target=server.serve_forever,
        daemon=True,
    )

    thread.start()

    return server


# ============================================================
# ENGINE
# ============================================================

def run(args):
    started = time.time()

    source = Path(args.image)

    if not source.exists():
        raise FileNotFoundError(source)

    original, original_size = load_image(
        str(source),
        args.max_side,
    )

    height, width, channels = original.shape

    reconstruction = np.zeros_like(original)
    residual = original.copy()

    families = candidate_families()

    if args.max_candidates > 0:
        families = families[:args.max_candidates]

    model = {
        "version": VERSION,
        "source": source.name,
        "source_dimensions": list(original_size),
        "analysis_dimensions": [width, height],
        "generator_type": "geometric_rc_ladder",
        "synthesis_type": "sparse_translated_impulse_fields",
        "generators": [],
    }

    STATE["original"] = display_image(original)
    STATE["reconstruction"] = display_image(reconstruction)
    STATE["residual"] = display_image(
        np.clip(0.5 + residual, 0.0, 1.0)
    )
    STATE["stages"] = args.stages
    STATE["status"] = "running"

    best_mse = mse(original, reconstruction)

    print(f"Image dimensions: {width} x {height}", flush=True)
    print(f"Candidate families: {len(families)}", flush=True)
    print(f"Initial MSE: {best_mse:.6f}", flush=True)

    kernel_cache = {}

    for stage in range(args.stages):
        stage_started = time.time()

        STATE["stage"] = stage + 1
        STATE["message"] = (
            f"Stage {stage + 1}: spectral candidate search"
        )

        print(
            f"\nSTAGE {stage + 1}/{args.stages}: candidate search",
            flush=True,
        )

        family, spectral_error, centers, target_power = (
            discover_best_family(
                residual,
                families,
                args.bins,
            )
        )

        if family is None:
            print("No valid family found.", flush=True)
            break

        key = (
            family["rho_num"],
            family["rho_den"],
            family["gamma_num"],
            family["gamma_den"],
            family["n"],
        )

        if key not in kernel_cache:
            kernel_cache[key] = make_generator(
                family,
                original.shape,
            )

        response, kernel = kernel_cache[key]

        print(
            f"  rho={family['rho']:.6f} "
            f"gamma={family['gamma']:.6f} "
            f"n={family['n']} "
            f"alpha={family['alpha']:.5f}",
            flush=True,
        )

        STATE["message"] = (
            f"Stage {stage + 1}: sparse whole-image fitting"
        )

        atoms, contribution = sparse_impulse_fit(
            residual,
            kernel,
            max_atoms=args.atoms_per_stage,
            threshold=args.atom_threshold,
        )

        if not atoms:
            print("  No useful atoms found; stopping.", flush=True)
            break

        proposed = np.clip(
            reconstruction + contribution,
            0.0,
            1.0,
        )

        proposed_mse = mse(original, proposed)

        if proposed_mse >= best_mse:
            print(
                f"  Rejected: MSE {proposed_mse:.6f} "
                f"not better than {best_mse:.6f}",
                flush=True,
            )
            break

        reconstruction = proposed
        residual = original - reconstruction
        best_mse = proposed_mse

        generator = {
            "family": {
                "rho_num": family["rho_num"],
                "rho_den": family["rho_den"],
                "gamma_num": family["gamma_num"],
                "gamma_den": family["gamma_den"],
                "rho": family["rho"],
                "gamma": family["gamma"],
                "n": family["n"],
                "alpha": family["alpha"],
            },
            "spectral_error": float(spectral_error),
            "atoms": atoms,
        }

        model["generators"].append(generator)

        model_bytes = save_model(
            model,
            args.output,
        )

        elapsed = time.time() - stage_started

        row = {
            "stage": stage + 1,
            "rho": family["rho"],
            "gamma": family["gamma"],
            "n": family["n"],
            "alpha": family["alpha"],
            "atoms": len(atoms),
            "mse": best_mse,
            "spectral_error": float(spectral_error),
            "model_bytes": model_bytes,
            "seconds": elapsed,
        }

        STATE["history"].append(row)
        STATE["mse"] = best_mse
        STATE["model_bytes"] = model_bytes
        STATE["elapsed"] = time.time() - started

        STATE["reconstruction"] = display_image(
            reconstruction
        )

        STATE["residual"] = display_image(
            np.clip(0.5 + residual * 1.5, 0.0, 1.0)
        )

        STATE["spectrum"] = display_image(
            normalized_display(np.log1p(np.abs(response)))
        )

        STATE["message"] = (
            f"Stage {stage + 1} complete: "
            f"{len(atoms)} atoms"
        )

        print(
            f"STAGE {stage + 1}/{args.stages} "
            f"rho={family['rho']:.6f} "
            f"gamma={family['gamma']:.6f} "
            f"n={family['n']} "
            f"alpha={family['alpha']:.5f} "
            f"atoms={len(atoms)} "
            f"MSE={best_mse:.7f} "
            f"spectral_error={spectral_error:.9g} "
            f"model_bytes={model_bytes} "
            f"seconds={elapsed:.2f}",
            flush=True,
        )

        if args.snapshots:
            Image.fromarray(
                (
                    np.clip(reconstruction, 0, 1) * 255
                ).astype(np.uint8)
            ).save(
                f"analog_stage_{stage + 1:02d}.png"
            )

        if best_mse <= args.target_mse:
            print("Target MSE reached.", flush=True)
            break

    final_bytes = save_model(
        model,
        args.output,
    )

    STATE["model_bytes"] = final_bytes
    STATE["mse"] = best_mse
    STATE["elapsed"] = time.time() - started
    STATE["status"] = "complete"
    STATE["message"] = "Synthesis complete"

    STATE["reconstruction"] = display_image(
        reconstruction
    )

    STATE["residual"] = display_image(
        np.clip(0.5 + residual * 1.5, 0.0, 1.0)
    )

    print("\nCOMPLETE", flush=True)
    print(f"Final MSE: {best_mse:.8f}", flush=True)
    print(f"Generators: {len(model['generators'])}", flush=True)
    print(f"Model: {args.output}", flush=True)
    print(f"Actual compressed model bytes: {final_bytes}", flush=True)


# ============================================================
# ENTRY POINT
# ============================================================

def main():
    parser = argparse.ArgumentParser(
        description="Analog whole-image fractal synthesis"
    )

    parser.add_argument("image")

    parser.add_argument("--stages", type=int, default=16)
    parser.add_argument("--bins", type=int, default=192)
    parser.add_argument("--iterations", type=int, default=100)

    parser.add_argument("--atoms-per-stage", type=int, default=64)
    parser.add_argument("--max-candidates", type=int, default=160)
    parser.add_argument("--max-side", type=int, default=512)

    parser.add_argument("--atom-threshold", type=float, default=0.012)
    parser.add_argument("--target-mse", type=float, default=0.0005)

    parser.add_argument("--port", type=int, default=8766)
    parser.add_argument(
        "--output",
        default="image_fractal_model.json",
    )
    parser.add_argument("--snapshots", action="store_true")

    args = parser.parse_args()

    if args.stages < 1:
        parser.error("--stages must be positive")

    if args.bins < 16:
        parser.error("--bins must be at least 16")

    if args.iterations < 1:
        parser.error("--iterations must be positive")

    if args.atoms_per_stage < 1:
        parser.error("--atoms-per-stage must be positive")

    print("ANALOG FRACTAL WORKBENCH", flush=True)
    print("========================", flush=True)
    print(f"Image: {args.image}", flush=True)
    print("Generator: geometric RC ladder", flush=True)
    print("Synthesis: whole-image sparse impulse fields", flush=True)
    print(f"Stages: {args.stages}", flush=True)
    print(f"Radial bins: {args.bins}", flush=True)
    print(f"Iterations: {args.iterations}", flush=True)
    print(f"Atoms/stage: {args.atoms_per_stage}", flush=True)

    server = start_dashboard(args.port)

    print(
        f"Dashboard: http://127.0.0.1:{args.port}",
        flush=True,
    )
    print(f"Model: {args.output}", flush=True)
    print("Press Ctrl+C to stop.\n", flush=True)

    try:
        run(args)

    except KeyboardInterrupt:
        STATE["status"] = "interrupted"
        STATE["message"] = "Interrupted by user"
        print("\nInterrupted.", flush=True)

    except Exception as exc:
        STATE["status"] = "error"
        STATE["message"] = str(exc)
        raise

    finally:
        server.shutdown()


if __name__ == "__main__":
    main()
