Spaces:
Runtime error

humanizer-engine / frontend /index.html
faseehsandhu's picture
add frontend and docker deployment for hf spaces
c327c7a
Raw History Blame Contribute Delete
26.2 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Humanization Engine</title>
<style>
/* ── Reset & Variables ─────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg-primary: #0f1117;
--bg-secondary: #1a1d27;
--bg-tertiary: #242836;
--border: #2e3347;
--border-focus: #5b6ef5;
--text-primary: #e4e6f0;
--text-secondary: #8b8fa3;
--text-muted: #5a5e73;
--accent: #5b6ef5;
--accent-hover: #4c5ce0;
--accent-glow: rgba(91, 110, 245, 0.15);
--success: #34d399;
--warning: #fbbf24;
--danger: #f87171;
--stat-bg: #1e2235;
--radius: 10px;
}
body {
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
font-size: 15px;
line-height: 1.6;
min-height: 100vh;
}
/* ── Health Banner ─────────────────────────────────── */
.health-banner {
position: fixed; top: 0; left: 0; right: 0; z-index: 1000;
padding: 10px 20px;
display: flex; align-items: center; justify-content: center; gap: 12px;
font-size: 14px; font-weight: 500;
transition: transform 0.3s ease;
}
.health-banner.hidden { transform: translateY(-100%); pointer-events: none; }
.health-banner.warning { background: #78350f; color: #fef3c7; }
.health-banner.error { background: #7f1d1d; color: #fecaca; }
.health-banner button {
background: none; border: none; color: inherit; font-size: 18px;
cursor: pointer; padding: 0 4px; opacity: 0.7;
}
.health-banner button:hover { opacity: 1; }
/* ── Layout ────────────────────────────────────────── */
.container {
max-width: 1400px;
margin: 0 auto;
padding: 32px 24px;
}
header {
text-align: center;
margin-bottom: 32px;
}
header h1 {
font-size: 28px;
font-weight: 700;
letter-spacing: -0.5px;
}
header p {
color: var(--text-secondary);
font-size: 14px;
margin-top: 4px;
}
.panels {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 24px;
}
.panel {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 20px;
display: flex;
flex-direction: column;
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
min-height: 28px;
}
.panel-title {
font-size: 14px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-secondary);
}
.word-count {
font-size: 13px;
color: var(--text-muted);
font-variant-numeric: tabular-nums;
}
.word-count.warn { color: var(--warning); }
.word-count.over { color: var(--danger); }
/* ── Textarea ──────────────────────────────────────── */
#input-text {
width: 100%;
min-height: 280px;
flex: 1;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text-primary);
font-family: inherit;
font-size: 15px;
line-height: 1.65;
padding: 14px 16px;
resize: vertical;
transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
#input-text:focus {
outline: none;
border-color: var(--border-focus);
box-shadow: 0 0 0 3px var(--accent-glow);
}
#input-text::placeholder { color: var(--text-muted); }
/* ── Controls ──────────────────────────────────────── */
.controls {
display: flex;
align-items: center;
gap: 12px;
margin-top: 14px;
flex-wrap: wrap;
}
.controls select {
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text-primary);
font-size: 14px;
padding: 10px 14px;
cursor: pointer;
}
.controls select:focus { outline: none; border-color: var(--border-focus); }
.btn-humanize {
flex: 1;
min-width: 140px;
background: var(--accent);
color: #fff;
border: none;
border-radius: 8px;
padding: 11px 28px;
font-size: 15px;
font-weight: 600;
cursor: pointer;
transition: background 0.15s ease, opacity 0.15s ease;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.btn-humanize:hover:not(:disabled) { background: var(--accent-hover); }
.btn-humanize:disabled { opacity: 0.5; cursor: not-allowed; }
.spinner-sm {
width: 16px; height: 16px;
border: 2px solid rgba(255,255,255,0.3);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
.hint {
width: 100%;
font-size: 12px;
color: var(--text-muted);
margin-top: 6px;
}
/* ── Output Area ───────────────────────────────────── */
.output-wrap {
position: relative;
flex: 1;
display: flex;
flex-direction: column;
}
#output-text {
width: 100%;
min-height: 280px;
flex: 1;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 8px;
padding: 14px 16px;
font-size: 15px;
line-height: 1.65;
white-space: pre-wrap;
word-break: break-word;
overflow-y: auto;
color: var(--text-primary);
}
#output-text.placeholder { color: var(--text-muted); font-style: italic; }
.btn-copy {
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text-secondary);
font-size: 13px;
padding: 4px 12px;
cursor: pointer;
transition: all 0.15s ease;
}
.btn-copy:hover { border-color: var(--accent); color: var(--text-primary); }
.btn-copy.copied { border-color: var(--success); color: var(--success); }
/* ── Loading Overlay ───────────────────────────────── */
.loading-overlay {
position: absolute;
inset: 0;
background: rgba(15, 17, 23, 0.85);
border-radius: 8px;
display: none;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 16px;
z-index: 10;
}
.loading-overlay.active { display: flex; }
.spinner {
width: 40px; height: 40px;
border: 3px solid var(--border);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
.loading-text {
font-size: 14px;
color: var(--text-secondary);
}
@keyframes spin { to { transform: rotate(360deg); } }
/* ── Stats Panel ───────────────────────────────────── */
.stats-section {
margin-top: 24px;
display: none;
}
.stats-section.visible { display: block; }
.stats-title {
font-size: 14px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-secondary);
margin-bottom: 14px;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 12px;
}
.stat-card {
background: var(--stat-bg);
border: 1px solid var(--border);
border-radius: 8px;
padding: 14px 16px;
}
.stat-label {
font-size: 12px;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.3px;
margin-bottom: 6px;
}
.stat-value {
font-size: 18px;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.stat-detail {
font-size: 12px;
color: var(--text-secondary);
margin-top: 4px;
}
.up { color: var(--success); }
.down { color: var(--danger); }
.neutral { color: var(--text-secondary); }
/* ── Error Toast ───────────────────────────────────── */
.error-toast {
position: fixed;
bottom: 24px;
right: 24px;
max-width: 420px;
background: #1c1012;
border: 1px solid #5c2020;
border-left: 4px solid var(--danger);
border-radius: 8px;
padding: 14px 18px;
z-index: 1000;
transform: translateX(calc(100% + 40px));
transition: transform 0.3s ease;
}
.error-toast.visible { transform: translateX(0); }
.error-toast-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 4px;
}
.error-toast-code {
font-size: 12px;
font-weight: 600;
color: var(--danger);
text-transform: uppercase;
}
.error-toast-dismiss {
background: none; border: none;
color: var(--text-muted); font-size: 16px;
cursor: pointer;
}
.error-toast-msg {
font-size: 14px;
color: var(--text-secondary);
line-height: 1.5;
}
/* ── Responsive ────────────────────────────────────── */
@media (max-width: 768px) {
.container { padding: 20px 16px; }
header h1 { font-size: 22px; }
.panels { grid-template-columns: 1fr; }
#input-text, #output-text { min-height: 200px; }
.stats-grid { grid-template-columns: 1fr 1fr; }
}
@media (max-width: 480px) {
.stats-grid { grid-template-columns: 1fr; }
.controls { flex-direction: column; }
.controls select, .btn-humanize { width: 100%; }
}
</style>
</head>
<body>
<!-- Health Banner -->
<div id="health-banner" class="health-banner hidden">
<span id="health-message"></span>
<button id="health-dismiss" aria-label="Dismiss">&times;</button>
</div>
<div class="container">
<header>
<h1>Humanization Engine</h1>
<p>Analysis-guided AI text rewriter</p>
</header>
<div class="panels">
<!-- Input Panel -->
<div class="panel">
<div class="panel-header">
<span class="panel-title">Input</span>
<span id="word-count" class="word-count">0 words</span>
</div>
<textarea id="input-text" placeholder="Paste your AI-generated text here..." spellcheck="false"></textarea>
<div class="controls">
<select id="mode-select" aria-label="Processing mode">
<option value="standard">Standard</option>
<option value="thorough">Thorough</option>
</select>
<button id="humanize-btn" class="btn-humanize" type="button">Humanize</button>
</div>
<div class="hint">50 &ndash; 5,000 words &middot; Ctrl+Enter to submit</div>
</div>
<!-- Output Panel -->
<div class="panel">
<div class="panel-header">
<span class="panel-title">Output</span>
<div style="display:flex;align-items:center;gap:10px;">
<button id="copy-btn" class="btn-copy" style="display:none;">Copy</button>
<span id="output-word-count" class="word-count"></span>
</div>
</div>
<div class="output-wrap">
<div id="output-text" class="placeholder" aria-live="polite">Paste your text and click Humanize to get started.</div>
<div id="loading-overlay" class="loading-overlay">
<div class="spinner"></div>
<div class="loading-text">Processing... <span id="elapsed-time">0.0s</span></div>
</div>
</div>
</div>
</div>
<!-- Stats Section -->
<div id="stats-section" class="stats-section">
<div class="stats-title">Processing Stats</div>
<div id="stats-grid" class="stats-grid"></div>
</div>
</div>
<!-- Error Toast -->
<div id="error-toast" class="error-toast" role="alert">
<div class="error-toast-header">
<span id="error-code" class="error-toast-code"></span>
<button id="error-dismiss" class="error-toast-dismiss" aria-label="Dismiss">&times;</button>
</div>
<div id="error-msg" class="error-toast-msg"></div>
</div>
<script>
/* ── State ──────────────────────────────────────────── */
const state = {
isProcessing: false,
processingStart: null,
timerInterval: null,
healthInterval: null,
errorTimeout: null,
};
/* ── DOM refs ───────────────────────────────────────── */
const $ = (s) => document.querySelector(s);
const inputText = $('#input-text');
const outputText = $('#output-text');
const humanizeBtn = $('#humanize-btn');
const modeSelect = $('#mode-select');
const wordCountEl = $('#word-count');
const outWordCount = $('#output-word-count');
const copyBtn = $('#copy-btn');
const loadingOvl = $('#loading-overlay');
const elapsedEl = $('#elapsed-time');
const statsSection = $('#stats-section');
const statsGrid = $('#stats-grid');
const healthBanner = $('#health-banner');
const healthMsg = $('#health-message');
const healthDismiss = $('#health-dismiss');
const errorToast = $('#error-toast');
const errorCode = $('#error-code');
const errorMsgEl = $('#error-msg');
const errorDismiss = $('#error-dismiss');
/* ── Utilities ──────────────────────────────────────── */
function countWords(text) {
return text.trim().split(/\s+/).filter(w => w.length > 0).length;
}
function debounce(fn, ms) {
let t;
return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); };
}
function fmt(n, d = 1) {
return n == null ? 'N/A' : Number(n).toFixed(d);
}
function fmtMs(ms) {
if (ms == null) return 'N/A';
return ms >= 1000 ? (ms / 1000).toFixed(1) + 's' : Math.round(ms) + 'ms';
}
/* ── Word Count ─────────────────────────────────────── */
function updateWordCount() {
const c = countWords(inputText.value);
wordCountEl.textContent = c + ' word' + (c !== 1 ? 's' : '');
wordCountEl.classList.toggle('warn', c > 0 && c < 50);
wordCountEl.classList.toggle('over', c > 5000);
}
/* ── Health Check ───────────────────────────────────── */
async function checkHealth() {
try {
const res = await fetch('/health');
const data = await res.json();
if (data.status === 'starting') {
showHealthBanner('Server is starting up. Models are loading, please wait...', 'warning');
humanizeBtn.disabled = true;
} else if (data.status === 'degraded') {
showHealthBanner('Server running in degraded mode. Some features may be unavailable.', 'warning');
humanizeBtn.disabled = false;
} else {
hideHealthBanner();
humanizeBtn.disabled = false;
}
} catch {
showHealthBanner('Cannot connect to server.', 'error');
humanizeBtn.disabled = true;
}
}
function showHealthBanner(msg, type) {
healthMsg.textContent = msg;
healthBanner.className = 'health-banner ' + type;
}
function hideHealthBanner() {
healthBanner.classList.add('hidden');
}
/* ── Error Toast ────────────────────────────────────── */
const ERROR_MESSAGES = {
INPUT_TOO_SHORT: 'Your text is too short. Please provide at least 50 words.',
INPUT_TOO_LONG: 'Your text is too long. Maximum is 5,000 words.',
RATE_LIMITED: 'Too many requests. Please wait a minute before trying again.',
LLM_TIMEOUT: 'The AI model timed out. Please try again.',
PROCESSING_ERROR:'A processing error occurred. The server may still be starting.',
NETWORK_ERROR: 'Network error. Could not reach the server.',
};
function showError(msg, code) {
clearTimeout(state.errorTimeout);
errorCode.textContent = code || 'ERROR';
errorMsgEl.textContent = msg;
errorToast.classList.add('visible');
state.errorTimeout = setTimeout(dismissError, 8000);
}
function dismissError() {
errorToast.classList.remove('visible');
clearTimeout(state.errorTimeout);
}
/* ── Loading State ──────────────────────────────────── */
function setLoading(on) {
if (on) {
loadingOvl.classList.add('active');
humanizeBtn.disabled = true;
humanizeBtn.innerHTML = '<div class="spinner-sm"></div> Processing...';
inputText.disabled = true;
state.processingStart = Date.now();
state.timerInterval = setInterval(() => {
const s = ((Date.now() - state.processingStart) / 1000).toFixed(1);
elapsedEl.textContent = s + 's';
}, 100);
} else {
loadingOvl.classList.remove('active');
humanizeBtn.disabled = false;
humanizeBtn.textContent = 'Humanize';
inputText.disabled = false;
clearInterval(state.timerInterval);
}
}
/* ── Humanize ───────────────────────────────────────── */
async function handleHumanize() {
if (state.isProcessing) return;
const text = inputText.value.trim();
const wc = countWords(text);
if (wc < 50) return showError(ERROR_MESSAGES.INPUT_TOO_SHORT, 'INPUT_TOO_SHORT');
if (wc > 5000) return showError(ERROR_MESSAGES.INPUT_TOO_LONG, 'INPUT_TOO_LONG');
state.isProcessing = true;
setLoading(true);
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 120000);
const res = await fetch('/humanize', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, mode: modeSelect.value }),
signal: controller.signal,
});
clearTimeout(timeout);
const data = await res.json();
if (data.success) {
displayOutput(data.output_text);
displayStats(data.stats);
} else {
const msg = ERROR_MESSAGES[data.code] || data.error || 'Unknown error';
showError(msg, data.code);
}
} catch (e) {
if (e.name === 'AbortError') {
showError('Request timed out after 2 minutes.', 'TIMEOUT');
} else {
showError(ERROR_MESSAGES.NETWORK_ERROR, 'NETWORK_ERROR');
}
} finally {
state.isProcessing = false;
setLoading(false);
}
}
/* ── Display Output ─────────────────────────────────── */
function displayOutput(text) {
outputText.textContent = text;
outputText.classList.remove('placeholder');
copyBtn.style.display = 'inline-block';
const wc = countWords(text);
outWordCount.textContent = wc + ' word' + (wc !== 1 ? 's' : '');
}
/* ── Display Stats ──────────────────────────────────── */
function displayStats(s) {
if (!s) return;
const arrow = ' \u2192 ';
const cards = [];
// Word count
const expClass = s.expansion_percentage <= 30 ? 'up' : s.expansion_percentage <= 40 ? 'neutral' : 'down';
cards.push(card('Words', `${s.input_word_count}${arrow}${s.output_word_count}`,
`<span class="${expClass}">+${fmt(s.expansion_percentage, 1)}% expansion</span>`));
// Perplexity
if (s.input_avg_perplexity != null || s.output_avg_perplexity != null) {
const diff = (s.output_avg_perplexity || 0) - (s.input_avg_perplexity || 0);
const cls = diff > 0 ? 'up' : diff < 0 ? 'down' : 'neutral';
cards.push(card('Perplexity', `${fmt(s.input_avg_perplexity)}${arrow}${fmt(s.output_avg_perplexity)}`,
`<span class="${cls}">${diff > 0 ? '\u2191' : '\u2193'} ${fmt(Math.abs(diff))}</span> (higher = more human)`));
}
// Burstiness
if (s.input_burstiness_cv != null || s.output_burstiness_cv != null) {
const diff = (s.output_burstiness_cv || 0) - (s.input_burstiness_cv || 0);
const cls = diff > 0 ? 'up' : diff < 0 ? 'down' : 'neutral';
cards.push(card('Burstiness CV', `${fmt(s.input_burstiness_cv, 2)}${arrow}${fmt(s.output_burstiness_cv, 2)}`,
`<span class="${cls}">${diff > 0 ? '\u2191' : '\u2193'} ${fmt(Math.abs(diff), 2)}</span> (higher = more varied)`));
}
// Processing time
cards.push(card('Total Time', fmtMs(s.processing_time_ms),
`S1: ${fmtMs(s.stage1_time_ms)} | S2: ${fmtMs(s.stage2_time_ms)} | S3: ${fmtMs(s.stage3_time_ms)}`));
// Instructions & risk
cards.push(card('Analysis', `${s.instructions_generated || 0} instructions`,
`${s.high_risk_sentences || 0} high-risk sentences`));
// Banned words
const bw = s.banned_words_found_in_output || [];
cards.push(card('Banned Words', `${s.banned_words_auto_fixed || 0} auto-fixed`,
bw.length > 0 ? `<span class="down">Remaining: ${bw.join(', ')}</span>` : 'None remaining'));
// LLM info
cards.push(card('LLM Used', s.llm_used || 'N/A',
`Variant: ${s.prompt_variant_used || 'N/A'}`));
statsGrid.innerHTML = cards.join('');
statsSection.classList.add('visible');
}
function card(label, value, detail) {
return `<div class="stat-card">
<div class="stat-label">${label}</div>
<div class="stat-value">${value}</div>
<div class="stat-detail">${detail || ''}</div>
</div>`;
}
/* ── Copy to Clipboard ──────────────────────────────── */
async function handleCopy() {
const text = outputText.textContent;
if (!text || outputText.classList.contains('placeholder')) return;
try {
await navigator.clipboard.writeText(text);
} catch {
const range = document.createRange();
range.selectNodeContents(outputText);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
document.execCommand('copy');
sel.removeAllRanges();
}
copyBtn.textContent = 'Copied!';
copyBtn.classList.add('copied');
setTimeout(() => { copyBtn.textContent = 'Copy'; copyBtn.classList.remove('copied'); }, 2000);
}
/* ── Init ───────────────────────────────────────────── */
document.addEventListener('DOMContentLoaded', () => {
inputText.addEventListener('input', debounce(updateWordCount, 50));
humanizeBtn.addEventListener('click', handleHumanize);
copyBtn.addEventListener('click', handleCopy);
healthDismiss.addEventListener('click', hideHealthBanner);
errorDismiss.addEventListener('click', dismissError);
inputText.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
handleHumanize();
}
});
updateWordCount();
checkHealth();
state.healthInterval = setInterval(checkHealth, 30000);
});
</script>
</body>
</html>