Add local web analysis dashboard
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
import argparse
|
||||
import json
|
||||
from dataclasses import asdict
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from importlib import resources
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from serato_doctor.crate_parser import load_library_crates
|
||||
from serato_doctor.health import analyze_health
|
||||
from serato_doctor.models.library import Library
|
||||
from serato_doctor.scanner import scan_filesystem
|
||||
|
||||
|
||||
MAX_REQUEST_BYTES = 64 * 1024
|
||||
STATIC_FILES = {
|
||||
"/": ("index.html", "text/html; charset=utf-8"),
|
||||
"/app.css": ("app.css", "text/css; charset=utf-8"),
|
||||
"/app.js": ("app.js", "text/javascript; charset=utf-8"),
|
||||
}
|
||||
|
||||
|
||||
def analyze_paths(
|
||||
serato: Path, music: Path, reference_roots: Iterable[Path] = ()
|
||||
) -> dict:
|
||||
serato = serato.expanduser()
|
||||
music = music.expanduser()
|
||||
reference_roots = tuple(root.expanduser() for root in reference_roots)
|
||||
if not serato.is_dir():
|
||||
raise ValueError(f"Serato folder does not exist: {serato}")
|
||||
if not music.is_dir():
|
||||
raise ValueError(f"Music folder does not exist: {music}")
|
||||
|
||||
crates = load_library_crates(serato, reference_roots)
|
||||
filesystem = scan_filesystem(music)
|
||||
library = Library.from_crates(
|
||||
crates,
|
||||
filesystem.tracks,
|
||||
filesystem.broken_symlinks,
|
||||
)
|
||||
report = analyze_health(library)
|
||||
result = asdict(report)
|
||||
result["score_basis"] = report.score_basis
|
||||
return result
|
||||
|
||||
|
||||
class SeratoDoctorHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None:
|
||||
asset = STATIC_FILES.get(self.path)
|
||||
if asset is None:
|
||||
self._json_response(404, {"error": "Not found"})
|
||||
return
|
||||
filename, content_type = asset
|
||||
content = (
|
||||
resources.files("serato_doctor.webui")
|
||||
.joinpath(filename)
|
||||
.read_bytes()
|
||||
)
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(content)))
|
||||
self.end_headers()
|
||||
self.wfile.write(content)
|
||||
|
||||
def do_POST(self) -> None:
|
||||
if self.path != "/api/analyze":
|
||||
self._json_response(404, {"error": "Not found"})
|
||||
return
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
if length <= 0 or length > MAX_REQUEST_BYTES:
|
||||
raise ValueError("Invalid request size")
|
||||
payload = json.loads(self.rfile.read(length))
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("Request body must be a JSON object")
|
||||
roots = [Path(value) for value in payload.get("reference_roots", [])]
|
||||
result = analyze_paths(
|
||||
Path(payload["serato"]), Path(payload["music"]), roots
|
||||
)
|
||||
except (KeyError, TypeError, json.JSONDecodeError, ValueError) as error:
|
||||
self._json_response(400, {"error": str(error)})
|
||||
return
|
||||
self._json_response(200, result)
|
||||
|
||||
def _json_response(self, status: int, payload: dict) -> None:
|
||||
content = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(content)))
|
||||
self.end_headers()
|
||||
self.wfile.write(content)
|
||||
|
||||
def log_message(self, format: str, *args: object) -> None:
|
||||
return
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(prog="serato-doctor-web")
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--port", type=int, default=8765)
|
||||
args = parser.parse_args()
|
||||
server = ThreadingHTTPServer((args.host, args.port), SeratoDoctorHandler)
|
||||
print(f"Serato Doctor web interface: http://{args.host}:{args.port}")
|
||||
print("Press Ctrl+C to stop.")
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
server.server_close()
|
||||
@@ -0,0 +1 @@
|
||||
"""Static assets for the local Serato Doctor web interface."""
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,54 @@
|
||||
const form = document.querySelector('#analysis-form');
|
||||
const button = document.querySelector('#analyze-button');
|
||||
const errorBox = document.querySelector('#error-message');
|
||||
const results = document.querySelector('#dashboard');
|
||||
|
||||
function expandHome(path) {
|
||||
return path.trim();
|
||||
}
|
||||
|
||||
function render(data) {
|
||||
document.querySelectorAll('[data-field]').forEach((element) => {
|
||||
const value = data[element.dataset.field];
|
||||
element.textContent = value ?? '—';
|
||||
});
|
||||
const score = data.score;
|
||||
document.querySelector('#health-score').textContent = score == null ? '—' : `${score}%`;
|
||||
document.querySelector('#score-ring').style.setProperty('--score', score ?? 0);
|
||||
document.querySelector('#health-message').textContent = score == null
|
||||
? 'Not enough data yet'
|
||||
: score >= 95 ? 'Looking excellent' : score >= 80 ? 'A few things need attention' : 'Review recommended';
|
||||
document.querySelector('#score-basis').textContent = data.score_basis;
|
||||
document.querySelector('#analysis-time').textContent = `Completed ${new Date().toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})}`;
|
||||
results.hidden = false;
|
||||
results.scrollIntoView({behavior: 'smooth', block: 'start'});
|
||||
}
|
||||
|
||||
form.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
errorBox.hidden = true;
|
||||
button.disabled = true;
|
||||
button.querySelector('span').textContent = 'Analyzing safely…';
|
||||
const roots = document.querySelector('#reference-roots').value
|
||||
.split('\n').map((value) => value.trim()).filter(Boolean);
|
||||
try {
|
||||
const response = await fetch('/api/analyze', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
serato: expandHome(document.querySelector('#serato-path').value),
|
||||
music: expandHome(document.querySelector('#music-path').value),
|
||||
reference_roots: roots,
|
||||
}),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Analysis failed');
|
||||
render(data);
|
||||
} catch (error) {
|
||||
errorBox.textContent = error.message;
|
||||
errorBox.hidden = false;
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.querySelector('span').textContent = 'Analyze library';
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="dark">
|
||||
<title>Serato Doctor</title>
|
||||
<link rel="stylesheet" href="/app.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="ambient ambient-one"></div>
|
||||
<div class="ambient ambient-two"></div>
|
||||
<div class="shell">
|
||||
<aside class="sidebar">
|
||||
<a class="brand" href="/" aria-label="Serato Doctor home">
|
||||
<span class="brand-mark">SD</span>
|
||||
<span><strong>Serato</strong><small>Doctor</small></span>
|
||||
</a>
|
||||
<nav aria-label="Primary navigation">
|
||||
<a class="nav-item active" href="#dashboard"><span>⌁</span> Dashboard</a>
|
||||
<a class="nav-item" href="#scan"><span>◎</span> New analysis</a>
|
||||
<a class="nav-item" href="#diagnostics"><span>◇</span> Diagnostics</a>
|
||||
</nav>
|
||||
<div class="safety-card">
|
||||
<span class="safety-icon">✓</span>
|
||||
<div><strong>Read-only mode</strong><p>Your library will not be modified.</p></div>
|
||||
</div>
|
||||
<div class="sidebar-foot">Local interface · v0.1</div>
|
||||
</aside>
|
||||
|
||||
<main>
|
||||
<header class="topbar">
|
||||
<div><p class="eyebrow">Library intelligence</p><h1>Good evening.</h1></div>
|
||||
<div class="status-pill"><span></span> Local & private</div>
|
||||
</header>
|
||||
|
||||
<section id="scan" class="scan-panel panel">
|
||||
<div class="panel-copy">
|
||||
<p class="eyebrow">Start here</p>
|
||||
<h2>Analyze your library</h2>
|
||||
<p>Point Serato Doctor at your Serato and music folders. We inspect references, duplicates, smart crates, and symlinks without changing a thing.</p>
|
||||
</div>
|
||||
<form id="analysis-form">
|
||||
<label>Serato folder
|
||||
<input id="serato-path" name="serato" value="~/Music/_Serato_" required>
|
||||
</label>
|
||||
<label>Music folder
|
||||
<input id="music-path" name="music" value="~/Music/Jukebox" required>
|
||||
</label>
|
||||
<label class="wide">Historical reference roots <span>optional · one per line</span>
|
||||
<textarea id="reference-roots" rows="2" placeholder="/Users/old-user/OneDrive/Jukebox"></textarea>
|
||||
</label>
|
||||
<button id="analyze-button" type="submit"><span>Analyze library</span><b>→</b></button>
|
||||
</form>
|
||||
<div id="error-message" class="error" role="alert" hidden></div>
|
||||
</section>
|
||||
|
||||
<section id="dashboard" class="results" aria-live="polite" hidden>
|
||||
<div class="section-heading"><div><p class="eyebrow">Latest analysis</p><h2>Library health</h2></div><span id="analysis-time"></span></div>
|
||||
<div class="hero-grid">
|
||||
<article class="score-card panel">
|
||||
<div class="score-ring" id="score-ring"><div><strong id="health-score">—</strong><span>health</span></div></div>
|
||||
<div><p class="score-label">Reference integrity</p><h3 id="health-message">Ready to analyze</h3><p id="score-basis">We only score evidence we can defend.</p></div>
|
||||
</article>
|
||||
<div class="metrics-grid">
|
||||
<article class="metric panel"><span>Tracks</span><strong data-field="disk_tracks">—</strong><small>audio files found</small></article>
|
||||
<article class="metric panel warning"><span>Broken references</span><strong data-field="missing_references">—</strong><small>static crate entries</small></article>
|
||||
<article class="metric panel"><span>Unused tracks</span><strong data-field="unused_tracks">—</strong><small>not referenced by crates</small></article>
|
||||
<article class="metric panel"><span>Suggested matches</span><strong data-field="suggested_matches">—</strong><small>explainable candidates</small></article>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="diagnostics" class="diagnostics panel">
|
||||
<div class="section-heading"><div><p class="eyebrow">Full picture</p><h2>Diagnostics</h2></div><span class="read-only-tag">No changes made</span></div>
|
||||
<div class="diagnostic-list">
|
||||
<div><span class="diag-icon violet">◇</span><p><strong>Crates</strong><small><b data-field="static_crates">—</b> static · <b data-field="smart_crates">—</b> smart · <b data-field="dynamic_references_excluded">—</b> dynamic references excluded</small></p></div>
|
||||
<div><span class="diag-icon amber">≋</span><p><strong>Duplicate filenames</strong><small><b data-field="duplicate_filename_groups">—</b> exact groups · <b data-field="duplicate_files">—</b> extra files</small></p></div>
|
||||
<div><span class="diag-icon blue">⌁</span><p><strong>Cloud conflicts</strong><small><b data-field="suspected_cloud_conflict_groups">—</b> suspected groups · <b data-field="suspected_cloud_conflict_files">—</b> extra files</small></p></div>
|
||||
<div><span class="diag-icon red">↗</span><p><strong>Broken symlinks</strong><small><b data-field="broken_symlinks">—</b> unresolved links</small></p></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
<script src="/app.js" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user