gng / app_demo.py
plexdx's picture
Upload app_demo.py
88cbe39 verified
"""
app_demo.py β€” Hugging Face Spaces interactive demo.
A standalone FastAPI app that provides:
1. The production WebSocket backend (from main.py)
2. A beautiful HTML/JS demo dashboard at /demo
β€” Live claim submission with animated results
β€” WebSocket connection indicator
β€” Color-coded verdict cards with confidence arcs
β€” No browser extension required to test
Mount order: /demo static HTML, /ws WebSocket, all other routes from main.py
"""
from __future__ import annotations
import os
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
# Re-export the main app with the demo page bolted on
from main import app as fact_app
# Inject the demo route
@fact_app.get("/demo", response_class=HTMLResponse, include_in_schema=False)
async def demo_page():
return HTMLResponse(DEMO_HTML)
@fact_app.get("/favicon.ico", include_in_schema=False)
async def favicon():
from fastapi.responses import Response
# 1x1 transparent gif
return Response(
content=b"GIF89a\x01\x00\x01\x00\x00\xff\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x00;",
media_type="image/gif",
)
DEMO_HTML = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>⚑ Fact & Hallucination Intelligence Engine</title>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap"/>
<style>
:root {
--bg: #07080f;
--surface: #0d0f1a;
--surface2: #111422;
--border: #1a1d2e;
--border2: #252840;
--text: #e8eaf6;
--text2: #7c83b0;
--text3: #3d4268;
--accent: #4f7cff;
--green: #22c55e;
--yellow: #eab308;
--red: #ef4444;
--purple: #a855f7;
--green-bg: rgba(34,197,94,0.08);
--yellow-bg: rgba(234,179,8,0.08);
--red-bg: rgba(239,68,68,0.08);
--purple-bg: rgba(168,85,247,0.08);
--radius: 12px;
--font: 'Space Grotesk', sans-serif;
--mono: 'JetBrains Mono', monospace;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html { scroll-behavior: smooth; }
body {
font-family: var(--font);
background: var(--bg);
color: var(--text);
min-height: 100vh;
overflow-x: hidden;
-webkit-font-smoothing: antialiased;
}
/* ── Animated grid background ── */
body::before {
content: '';
position: fixed; inset: 0; z-index: 0; pointer-events: none;
background-image:
linear-gradient(rgba(79,124,255,0.03) 1px, transparent 1px),
linear-gradient(90deg, rgba(79,124,255,0.03) 1px, transparent 1px);
background-size: 48px 48px;
mask-image: radial-gradient(ellipse 80% 60% at 50% 0%, black 40%, transparent 100%);
}
.noise {
position: fixed; inset: 0; z-index: 0; pointer-events: none; opacity: 0.025;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-repeat: repeat;
background-size: 256px;
}
main { position: relative; z-index: 1; max-width: 900px; margin: 0 auto; padding: 40px 24px 80px; }
/* ── Header ── */
header { text-align: center; margin-bottom: 48px; }
.logo-row {
display: flex; align-items: center; justify-content: center; gap: 12px;
margin-bottom: 12px;
}
.logo-icon {
width: 44px; height: 44px; border-radius: 10px;
background: linear-gradient(135deg, #1a2040 0%, #0d1030 100%);
border: 1px solid rgba(79,124,255,0.3);
display: flex; align-items: center; justify-content: center;
font-size: 22px;
box-shadow: 0 0 30px rgba(79,124,255,0.15);
}
h1 {
font-size: clamp(22px, 4vw, 32px);
font-weight: 700; letter-spacing: -0.02em;
background: linear-gradient(135deg, #e8eaf6 0%, #7c83b0 100%);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
background-clip: text;
}
.subtitle {
color: var(--text2); font-size: 14px; max-width: 520px;
margin: 0 auto; line-height: 1.6;
}
/* ── Status bar ── */
.status-bar {
display: flex; align-items: center; justify-content: center;
gap: 8px; margin-top: 20px;
font-size: 12px; color: var(--text2);
font-family: var(--mono);
}
.status-dot {
width: 8px; height: 8px; border-radius: 50%; background: var(--text3);
transition: background 400ms;
}
.status-dot.connected { background: var(--green); box-shadow: 0 0 8px var(--green); animation: pulse 2s infinite; }
.status-dot.reconnecting { background: var(--yellow); animation: spin 1s linear infinite; }
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.4} }
@keyframes spin { from{transform:rotate(0)} to{transform:rotate(360deg)} }
/* ── Input section ── */
.input-card {
background: var(--surface);
border: 1px solid var(--border2);
border-radius: var(--radius);
padding: 20px;
margin-bottom: 24px;
box-shadow: 0 4px 24px rgba(0,0,0,0.4);
transition: border-color 300ms;
}
.input-card:focus-within { border-color: rgba(79,124,255,0.4); }
.input-header {
display: flex; align-items: center; justify-content: space-between;
margin-bottom: 12px;
}
.input-label { font-size: 12px; font-weight: 600; color: var(--text2); letter-spacing: 0.08em; text-transform: uppercase; }
.platform-select {
display: flex; gap: 6px;
}
.platform-btn {
padding: 3px 10px; border-radius: 20px; font-size: 11px; font-weight: 600;
cursor: pointer; border: 1px solid var(--border2);
background: transparent; color: var(--text2);
transition: all 150ms; font-family: var(--font);
}
.platform-btn.active {
background: rgba(79,124,255,0.15); border-color: rgba(79,124,255,0.5);
color: #7da4ff;
}
textarea {
width: 100%; min-height: 90px; padding: 12px;
background: var(--surface2); border: 1px solid var(--border);
border-radius: 8px; color: var(--text);
font-family: var(--mono); font-size: 13px; line-height: 1.6;
resize: vertical; outline: none;
transition: border-color 200ms;
}
textarea::placeholder { color: var(--text3); }
textarea:focus { border-color: rgba(79,124,255,0.4); }
.input-footer {
display: flex; align-items: center; justify-content: space-between;
margin-top: 12px;
}
.char-count { font-size: 11px; color: var(--text3); font-family: var(--mono); }
.analyze-btn {
display: flex; align-items: center; gap: 8px;
padding: 10px 22px; border-radius: 8px;
background: linear-gradient(135deg, #3060e0, #4f7cff);
border: none; color: white; font-family: var(--font);
font-size: 13px; font-weight: 600; cursor: pointer;
box-shadow: 0 4px 20px rgba(79,124,255,0.3);
transition: transform 150ms, box-shadow 150ms;
}
.analyze-btn:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 6px 28px rgba(79,124,255,0.4); }
.analyze-btn:active:not(:disabled) { transform: scale(0.97); }
.analyze-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
/* ── Quick examples ── */
.examples-row {
display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 24px;
}
.example-chip {
padding: 5px 12px; border-radius: 20px; font-size: 11px;
border: 1px solid var(--border2); background: var(--surface);
color: var(--text2); cursor: pointer; font-family: var(--font);
transition: all 150ms; white-space: nowrap;
}
.example-chip:hover {
background: var(--surface2); border-color: var(--border2);
color: var(--text);
}
.example-chip .dot {
display: inline-block; width: 6px; height: 6px; border-radius: 50%;
margin-right: 5px; vertical-align: middle;
}
/* ── Results ── */
#results { display: flex; flex-direction: column; gap: 14px; }
.result-card {
background: var(--surface);
border-radius: var(--radius);
overflow: hidden;
border: 1px solid var(--border2);
animation: slideIn 350ms cubic-bezier(0.34, 1.56, 0.64, 1) both;
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}
@keyframes slideIn {
from { opacity: 0; transform: translateY(16px) scale(0.97); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.result-header {
display: flex; align-items: center; gap: 12px;
padding: 14px 16px;
}
.result-icon {
width: 36px; height: 36px; border-radius: 50%;
display: flex; align-items: center; justify-content: center;
font-size: 16px; font-weight: 700; flex-shrink: 0;
border: 2px solid;
}
.result-meta { flex: 1; min-width: 0; }
.result-verdict { font-size: 14px; font-weight: 600; color: var(--text); }
.result-text {
font-size: 11px; color: var(--text2); margin-top: 2px;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.result-confidence {
display: flex; align-items: center; gap: 6px;
font-size: 20px; font-weight: 700;
font-family: var(--mono); flex-shrink: 0;
}
.result-body {
padding: 0 16px 14px;
border-top: 1px solid var(--border);
}
.result-explanation {
font-size: 13px; color: var(--text2); line-height: 1.6;
margin: 12px 0 10px; padding: 10px 12px;
background: var(--surface2); border-radius: 8px;
border-left: 3px solid;
}
.result-meta-row {
display: flex; align-items: center; gap: 12px;
margin-bottom: 10px;
}
.trust-bar-wrap { flex: 1; }
.trust-bar-label { font-size: 10px; color: var(--text3); margin-bottom: 4px; font-family: var(--mono); }
.trust-bar-track { height: 4px; background: var(--border2); border-radius: 2px; overflow: hidden; }
.trust-bar-fill { height: 100%; border-radius: 2px; transition: width 800ms cubic-bezier(0.4,0,0.2,1); }
.badge-row { display: flex; flex-wrap: wrap; gap: 6px; }
.badge {
padding: 2px 8px; border-radius: 4px; font-size: 10px; font-weight: 600;
font-family: var(--mono); letter-spacing: 0.05em;
text-transform: uppercase;
}
.sources-list { display: flex; flex-direction: column; gap: 4px; }
.source-item {
display: flex; align-items: center; gap: 6px;
padding: 5px 8px; border-radius: 6px;
background: rgba(255,255,255,0.02);
border: 1px solid var(--border);
text-decoration: none; color: #60a5fa; font-size: 11px;
transition: background 120ms;
overflow: hidden;
}
.source-item:hover { background: rgba(96,165,250,0.06); }
.source-domain { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.processing-time { font-size: 10px; color: var(--text3); font-family: var(--mono); margin-top: 8px; text-align: right; }
/* ── Spinner ── */
.spinner-card {
background: var(--surface); border: 1px solid var(--border2);
border-radius: var(--radius); padding: 24px;
display: flex; align-items: center; gap: 16px;
animation: fadeIn 200ms ease;
}
@keyframes fadeIn { from{opacity:0} to{opacity:1} }
.spinner {
width: 28px; height: 28px; border-radius: 50%;
border: 2.5px solid var(--border2); border-top-color: var(--accent);
animation: spin 0.9s linear infinite; flex-shrink: 0;
}
.spinner-text { color: var(--text2); font-size: 13px; }
.spinner-stage { color: var(--text3); font-size: 11px; font-family: var(--mono); margin-top: 3px; }
/* ── Stats strip ── */
.stats-strip {
display: grid; grid-template-columns: repeat(4,1fr); gap: 1px;
background: var(--border); border-radius: var(--radius);
overflow: hidden; margin-bottom: 24px;
border: 1px solid var(--border);
}
.stat-cell {
background: var(--surface); padding: 14px 12px; text-align: center;
}
.stat-value { font-size: 22px; font-weight: 700; font-family: var(--mono); color: var(--text); }
.stat-label { font-size: 10px; color: var(--text3); text-transform: uppercase; letter-spacing: 0.1em; margin-top: 2px; }
/* ── Color palette indicator ── */
.palette-row {
display: flex; gap: 8px; margin-bottom: 24px;
flex-wrap: wrap;
}
.palette-item {
flex: 1; min-width: 120px; padding: 12px;
border-radius: 8px; border: 1px solid; display: flex; align-items: center; gap: 8px;
}
.palette-dot { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; }
.palette-label { font-size: 12px; font-weight: 600; }
.palette-desc { font-size: 10px; margin-top: 1px; opacity: 0.7; }
@media (max-width: 600px) {
.stats-strip { grid-template-columns: 1fr 1fr; }
.platform-select { flex-wrap: wrap; }
.palette-row { flex-direction: column; }
}
</style>
</head>
<body>
<div class="noise"></div>
<main>
<!-- Header -->
<header>
<div class="logo-row">
<div class="logo-icon">⚑</div>
<h1>Fact & Hallucination Intelligence Engine</h1>
</div>
<p class="subtitle">Real-time claim verification across Twitter/X, Instagram, YouTube, and AI chat interfaces. Powered by Groq Β· BGE-M3 Β· Qdrant Β· Memgraph.</p>
<div class="status-bar">
<div class="status-dot" id="statusDot"></div>
<span id="statusText">Connecting…</span>
<span style="color:var(--text3)">Β·</span>
<span id="clientIdSpan" style="color:var(--text3)">β€”</span>
</div>
</header>
<!-- Stats -->
<div class="stats-strip">
<div class="stat-cell"><div class="stat-value" id="statTotal">0</div><div class="stat-label">Analyzed</div></div>
<div class="stat-cell"><div class="stat-value" id="statFlagged" style="color:var(--red)">0</div><div class="stat-label">Flagged</div></div>
<div class="stat-cell"><div class="stat-value" id="statCached" style="color:var(--accent)">0</div><div class="stat-label">Cached</div></div>
<div class="stat-cell"><div class="stat-value" id="statAvgMs">β€”</div><div class="stat-label">Avg ms</div></div>
</div>
<!-- Color key -->
<div class="palette-row">
<div class="palette-item" style="border-color:rgba(34,197,94,0.3);background:rgba(34,197,94,0.05)">
<div class="palette-dot" style="background:#22c55e"></div>
<div><div class="palette-label" style="color:#22c55e">Verified</div><div class="palette-desc" style="color:#22c55e">Widely corroborated</div></div>
</div>
<div class="palette-item" style="border-color:rgba(234,179,8,0.3);background:rgba(234,179,8,0.05)">
<div class="palette-dot" style="background:#eab308"></div>
<div><div class="palette-label" style="color:#eab308">Unverified</div><div class="palette-desc" style="color:#eab308">Breaking / contested</div></div>
</div>
<div class="palette-item" style="border-color:rgba(239,68,68,0.3);background:rgba(239,68,68,0.05)">
<div class="palette-dot" style="background:#ef4444"></div>
<div><div class="palette-label" style="color:#ef4444">Misleading</div><div class="palette-desc" style="color:#ef4444">Debunked / false</div></div>
</div>
<div class="palette-item" style="border-color:rgba(168,85,247,0.3);background:rgba(168,85,247,0.05)">
<div class="palette-dot" style="background:#a855f7"></div>
<div><div class="palette-label" style="color:#a855f7">AI Hallucination</div><div class="palette-desc" style="color:#a855f7">Fabricated / impossible</div></div>
</div>
</div>
<!-- Input -->
<div class="input-card">
<div class="input-header">
<span class="input-label">Enter a claim to analyze</span>
<div class="platform-select" id="platformSelect">
<button class="platform-btn active" data-platform="web">Web</button>
<button class="platform-btn" data-platform="x">X / Twitter</button>
<button class="platform-btn" data-platform="youtube">YouTube</button>
<button class="platform-btn" data-platform="chatgpt">AI Chat</button>
</div>
</div>
<textarea id="claimInput" placeholder="e.g. The unemployment rate hit 4.2% in September 2024, the highest since early 2022…" maxlength="800" rows="3"></textarea>
<div class="input-footer">
<span class="char-count"><span id="charCount">0</span> / 800</span>
<button class="analyze-btn" id="analyzeBtn" onclick="analyze()">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
<circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
</svg>
Analyze
</button>
</div>
</div>
<!-- Quick examples -->
<div class="examples-row" id="examplesRow">
<span style="font-size:11px;color:var(--text3);align-self:center;margin-right:4px;font-weight:600;text-transform:uppercase;letter-spacing:0.08em">Try:</span>
</div>
<!-- Results -->
<div id="results"></div>
</main>
<script>
// ── Config ────────────────────────────────────────────────────────────────────
const WS_BASE = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const WS_URL = `${WS_BASE}//${window.location.host}`;
const CLIENT_ID = 'demo-' + Math.random().toString(36).slice(2,10);
// ── State ─────────────────────────────────────────────────────────────────────
let ws = null;
let wsStatus = 'offline';
let selectedPlatform = 'web';
let stats = { total: 0, flagged: 0, cached: 0, totalMs: 0 };
let reconnectDelay = 1000;
// ── Quick examples ────────────────────────────────────────────────────────────
const EXAMPLES = [
{ text: "The US unemployment rate hit 4.2% in September 2024, the highest since early 2022.", color: "green" },
{ text: "Scientists discovered vaccines contain microchips that transmit location data to governments.", color: "red" },
{ text: "SpaceX's Starship achieved its first successful ocean splashdown on its fourth integrated flight test.", color: "green" },
{ text: "According to a Harvard study published in Nature, AI systems have achieved human-level sentience as of 2024.", color: "purple", platform: "chatgpt" },
{ text: "BREAKING: WHO declares emergency as novel pathogen spreads to 15 countries overnight.", color: "yellow" },
{ text: "Eating 3 tablespoons of olive oil daily reduces Alzheimer's risk by 90% β€” study shows.", color: "red" },
];
function initExamples() {
const row = document.getElementById('examplesRow');
EXAMPLES.forEach(ex => {
const colors = { green:'#22c55e', yellow:'#eab308', red:'#ef4444', purple:'#a855f7' };
const btn = document.createElement('button');
btn.className = 'example-chip';
btn.innerHTML = `<span class="dot" style="background:${colors[ex.color]}"></span>${ex.text.slice(0,42)}…`;
btn.onclick = () => {
document.getElementById('claimInput').value = ex.text;
updateCharCount();
if (ex.platform) selectPlatform(ex.platform);
analyze();
};
row.appendChild(btn);
});
}
// ── Platform selector ─────────────────────────────────────────────────────────
document.getElementById('platformSelect').addEventListener('click', e => {
const btn = e.target.closest('[data-platform]');
if (btn) selectPlatform(btn.dataset.platform);
});
function selectPlatform(p) {
selectedPlatform = p;
document.querySelectorAll('.platform-btn').forEach(b => {
b.classList.toggle('active', b.dataset.platform === p);
});
}
// ── Char count ────────────────────────────────────────────────────────────────
const claimInput = document.getElementById('claimInput');
claimInput.addEventListener('input', updateCharCount);
function updateCharCount() {
document.getElementById('charCount').textContent = claimInput.value.length;
}
// ── Enter to submit ───────────────────────────────────────────────────────────
claimInput.addEventListener('keydown', e => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) analyze();
});
// ── WebSocket ─────────────────────────────────────────────────────────────────
function connect() {
setStatus('reconnecting');
try {
ws = new WebSocket(`${WS_URL}/ws/${CLIENT_ID}`);
ws.onopen = () => {
setStatus('connected');
reconnectDelay = 1000;
document.getElementById('clientIdSpan').textContent = CLIENT_ID;
};
ws.onmessage = e => {
try { handleMessage(JSON.parse(e.data)); } catch {}
};
ws.onclose = () => {
setStatus('offline');
setTimeout(connect, reconnectDelay);
reconnectDelay = Math.min(reconnectDelay * 2, 30000);
};
ws.onerror = () => ws.close();
} catch {
setStatus('offline');
setTimeout(connect, reconnectDelay);
}
}
function setStatus(s) {
wsStatus = s;
const dot = document.getElementById('statusDot');
const txt = document.getElementById('statusText');
dot.className = 'status-dot ' + s;
const labels = { connected:'Engine online', reconnecting:'Connecting…', offline:'Offline' };
txt.textContent = labels[s] || s;
}
// ── Analyze ───────────────────────────────────────────────────────────────────
function analyze() {
const text = claimInput.value.trim();
if (!text || text.length < 20) {
claimInput.style.borderColor = 'rgba(239,68,68,0.5)';
setTimeout(() => claimInput.style.borderColor = '', 1000);
return;
}
const btn = document.getElementById('analyzeBtn');
btn.disabled = true;
btn.innerHTML = `<div class="spinner" style="width:14px;height:14px;border-width:2px"></div> Analyzing…`;
const spinnerId = 'spinner-' + Date.now();
prependSpinner(spinnerId, text);
const payload = {
client_id: CLIENT_ID,
claims: [text],
platform: selectedPlatform,
timestamp: Date.now() / 1000,
};
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(payload));
} else {
// Fallback: HTTP polling via /analyze endpoint if available
fetch('/analyze', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
.then(r => r.json())
.then(data => { if (data.results) handleResults(data.results, spinnerId); })
.catch(() => removeSpinner(spinnerId))
.finally(() => resetBtn());
}
// Timeout safety
setTimeout(() => { removeSpinner(spinnerId); resetBtn(); }, 15000);
}
function resetBtn() {
const btn = document.getElementById('analyzeBtn');
btn.disabled = false;
btn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg> Analyze`;
}
function handleMessage(msg) {
if (msg.type === 'analysis_batch') {
// Find active spinner
const spinner = document.querySelector('[data-spinner]');
const spinnerId = spinner?.id;
handleResults(msg.results, spinnerId);
resetBtn();
}
}
function handleResults(results, spinnerId) {
if (spinnerId) removeSpinner(spinnerId);
results.forEach(r => {
renderResult(r);
updateStats(r);
});
}
// ── Spinner ───────────────────────────────────────────────────────────────────
const STAGES = ['Classifying claim…', 'Searching evidence…', 'Scoring trust graph…', 'Running agents…'];
function prependSpinner(id, text) {
const container = document.getElementById('results');
const div = document.createElement('div');
div.id = id;
div.setAttribute('data-spinner', '1');
div.className = 'spinner-card';
div.innerHTML = `
<div class="spinner"></div>
<div>
<div class="spinner-text">${escHtml(text.slice(0,80))}${text.length>80?'…':''}</div>
<div class="spinner-stage" id="${id}-stage">${STAGES[0]}</div>
</div>`;
container.prepend(div);
// Animate through stages
let si = 0;
const iv = setInterval(() => {
si = (si+1) % STAGES.length;
const el = document.getElementById(`${id}-stage`);
if (el) el.textContent = STAGES[si]; else clearInterval(iv);
}, 900);
div._stageInterval = iv;
}
function removeSpinner(id) {
const el = document.getElementById(id);
if (el) { clearInterval(el._stageInterval); el.remove(); }
}
// ── Result card ───────────────────────────────────────────────────────────────
const COLOR_CFG = {
green: { hex:'#22c55e', bg:'var(--green-bg)', emoji:'βœ“', label:'Verified' },
yellow: { hex:'#eab308', bg:'var(--yellow-bg)', emoji:'~', label:'Unverified' },
red: { hex:'#ef4444', bg:'var(--red-bg)', emoji:'βœ—', label:'Misleading' },
purple: { hex:'#a855f7', bg:'var(--purple-bg)', emoji:'?', label:'AI Hallucination' },
};
function renderResult(r) {
const cfg = COLOR_CFG[r.color] || COLOR_CFG.yellow;
const trustPct = Math.round((r.trust_score || 0.5) * 100);
const container = document.getElementById('results');
const card = document.createElement('div');
card.className = 'result-card';
card.style.borderColor = cfg.hex + '44';
card.style.animationDelay = '0ms';
const sourcesHtml = (r.sources || []).slice(0,3).map(url => {
let domain;
try { domain = new URL(url).hostname.replace('www.',''); } catch { domain = url.slice(0,30); }
return `<a class="source-item" href="${escHtml(url)}" target="_blank" rel="noreferrer">
<img src="https://www.google.com/s2/favicons?domain=${domain}&sz=16" width="12" height="12" style="border-radius:2px;flex-shrink:0" onerror="this.style.display='none'"/>
<span class="source-domain">${escHtml(domain)}</span>
</a>`;
}).join('');
const badges = [
r.cached ? `<span class="badge" style="background:rgba(79,124,255,0.15);color:#7da4ff">cached</span>` : '',
`<span class="badge" style="background:rgba(255,255,255,0.04);color:var(--text2)">${escHtml(r.platform||'web')}</span>`,
r.processing_ms ? `<span class="badge" style="background:rgba(255,255,255,0.03);color:var(--text3)">${Math.round(r.processing_ms)}ms</span>` : '',
].filter(Boolean).join('');
card.innerHTML = `
<div class="result-header" style="background:${cfg.bg}">
<div class="result-icon" style="border-color:${cfg.hex};color:${cfg.hex};background:${cfg.hex}15">${cfg.emoji}</div>
<div class="result-meta">
<div class="result-verdict" style="color:${cfg.hex}">${escHtml(r.verdict || cfg.label)}</div>
<div class="result-text">${escHtml((r.claim_text||'').slice(0,90))}${(r.claim_text||'').length>90?'…':''}</div>
</div>
<div class="result-confidence" style="color:${cfg.hex}">${r.confidence}<span style="font-size:11px;color:var(--text3);margin-left:1px">%</span></div>
</div>
<div class="result-body">
<div class="result-explanation" style="border-left-color:${cfg.hex}">${escHtml(r.explanation||'No explanation available.')}</div>
<div class="result-meta-row">
<div class="trust-bar-wrap">
<div class="trust-bar-label">Trust Score Β· ${trustPct}%</div>
<div class="trust-bar-track"><div class="trust-bar-fill" style="width:0%;background:${cfg.hex}" data-target="${trustPct}"></div></div>
</div>
</div>
${badges ? `<div class="badge-row" style="margin-bottom:10px">${badges}</div>` : ''}
${sourcesHtml ? `<div class="sources-list">${sourcesHtml}</div>` : ''}
</div>`;
container.prepend(card);
// Animate trust bar after paint
requestAnimationFrame(() => {
const fill = card.querySelector('.trust-bar-fill');
if (fill) fill.style.width = fill.dataset.target + '%';
});
}
// ── Stats ─────────────────────────────────────────────────────────────────────
function updateStats(r) {
stats.total++;
if (r.color === 'red' || r.color === 'purple') stats.flagged++;
if (r.cached) stats.cached++;
if (r.processing_ms) stats.totalMs += r.processing_ms;
document.getElementById('statTotal').textContent = stats.total;
document.getElementById('statFlagged').textContent = stats.flagged;
document.getElementById('statCached').textContent = stats.cached;
const avgMs = stats.total > 0 ? Math.round(stats.totalMs / stats.total) : 0;
document.getElementById('statAvgMs').textContent = avgMs > 0 ? avgMs + 'ms' : 'β€”';
}
function escHtml(s) {
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
// ── Init ──────────────────────────────────────────────────────────────────────
initExamples();
connect();
</script>
</body>
</html>
"""
# This module is imported by Dockerfile CMD via main.py
# For Hugging Face, rename this file to main.py or import it as the entry point.