Spaces:
Running
Running
File size: 6,523 Bytes
d822c60 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | const $ = (id) => document.getElementById(id);
const draft = $('draft'), output = $('output'), run = $('rewrite');
let busy = false;
let activeJob;
let clientPromise;
const examples = {
email: 'I wanted to reach out to provide an update regarding our upcoming meeting. The meeting is scheduled for October 21 at 2:00 PM. We will discuss the three proposals that Maya submitted on Friday. Please review the attached materials beforehand so that we can have a productive discussion.',
report: 'It is important to note that the pilot project demonstrated a number of positive outcomes. Over the course of six weeks, the team processed 240 support requests. The average response time decreased from 18 hours to 11 hours. However, these findings are preliminary, and a larger study is needed before we draw firm conclusions.',
chinese: '我想向大家汇报一下项目的最新进展。经过团队的共同努力,我们在六周内处理了240条客户请求,平均回复时间从18小时缩短到了11小时。不过,这些结果仍然是初步的,我们需要更多数据才能得出明确的结论。'
};
function status(message, kind = '') {
$('status').textContent = message;
$('status').dataset.kind = kind;
}
function counts() {
const words = draft.value.trim().split(/\s+/u).filter(Boolean).length;
$('count').textContent = `${words} words · ${draft.value.length.toLocaleString()} characters`;
}
function setBusy(value) {
busy = value;
run.disabled = value;
run.textContent = value ? 'Rewriting…' : 'Rewrite draft ↗';
draft.readOnly = value;
$('clear').disabled = value;
document.querySelectorAll('.sample').forEach(button => button.disabled = value);
document.querySelector('.workspace').setAttribute('aria-busy', String(value));
}
function resetResult() {
output.value = '';
$('copy').disabled = $('download').disabled = true;
$('result-info').textContent = 'Fresh wording. Same intended meaning.';
}
async function rewrite() {
if (busy) return;
const text = draft.value.trim();
if (!text) { status('Paste a draft or choose an example first.', 'error'); draft.focus(); return; }
const han = (text.match(/\p{Script=Han}/gu) || []).length;
const latin = text.replace(/\p{Script=Han}/gu, ' ').trim().split(/\s+/u).filter(Boolean).length;
if (latin > 700 || han > 1200 || text.length > 12000) {
status('This draft is too long. Use up to 700 English words or 1,200 Chinese characters; split longer documents into shorter passages.', 'error'); return;
}
resetResult(); setBusy(true);
status('Connecting to the author’s demo. Your draft will be sent there for processing…');
const started = performance.now();
try {
// Load on demand so the editor remains usable if the CDN is unavailable.
if (!clientPromise) clientPromise = import('https://cdn.jsdelivr.net/npm/@gradio/client@2.7.1/+esm')
.then(({ Client }) => Client.connect('jialinyyzz/humanizer'))
.catch(error => { clientPromise = undefined; throw error; });
const client = await clientPromise;
activeJob = client.submit('/humanize', { draft: text });
let result;
for await (const event of activeJob) {
if (event.type === 'status') {
if (event.stage === 'error') throw new Error(event.message || 'The model service could not process this draft.');
if (event.stage === 'pending') status(`Waiting for a GPU${Number.isFinite(event.position) ? ` · queue position ${event.position + 1}` : ''}. Keep this page open…`);
if (event.stage === 'generating') status('The model is rewriting your draft. Longer passages can take a minute or two…');
}
if (event.type === 'data') result = event.data?.[0];
}
if (!result || typeof result.text !== 'string' || !result.text.trim()) throw new Error('The service returned no rewrite. Please try again.');
output.value = result.text;
$('copy').disabled = $('download').disabled = false;
const elapsed = Math.round((performance.now() - started) / 1000);
$('result-info').textContent = `${result.text.length.toLocaleString()} characters · ${elapsed}s including queue`;
const missing = result.missing_numbers || [], added = result.added_numbers || [];
const warnings = [];
if (result.truncated) warnings.push('The rewrite may be incomplete because generation reached its limit.');
if (missing.length) warnings.push(`Numbers missing from rewrite: ${missing.join(', ')}.`);
if (added.length) warnings.push(`New numbers in rewrite: ${added.join(', ')}.`);
status(warnings.length ? `${warnings.join(' ')} Review the result carefully.` : 'Rewrite ready. Review names, dates, numbers, and meaning before using it. Numeric checks do not verify every fact.', warnings.length ? 'warning' : '');
} catch (error) {
const message = typeof error?.message === 'string' ? error.message : String(error);
status(`Could not finish: ${message.slice(0, 700)}. The upstream demo may be busy, asleep, or out of GPU quota. Try again or open the author’s demo below.`, 'error');
} finally { activeJob = undefined; setBusy(false); }
}
draft.addEventListener('input', () => {
counts(); resetResult(); status('Ready to rewrite this draft.');
});
document.querySelectorAll('.sample').forEach(button => button.addEventListener('click', () => {
draft.value = examples[button.dataset.example]; counts(); resetResult(); status('Example loaded. Select Rewrite draft to run the model.'); draft.focus();
}));
$('clear').addEventListener('click', () => { draft.value = ''; resetResult(); counts(); status('Ready for a fresh draft.'); draft.focus(); });
run.addEventListener('click', rewrite);
draft.addEventListener('keydown', event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); rewrite(); } });
$('copy').addEventListener('click', async () => {
try { await navigator.clipboard.writeText(output.value); status('Rewrite copied.'); }
catch { output.focus(); output.select(); status('Clipboard access is unavailable. The rewrite is selected; press Ctrl+C or ⌘C to copy.'); }
});
$('download').addEventListener('click', () => {
const url = URL.createObjectURL(new Blob([output.value], { type: 'text/plain;charset=utf-8' }));
const anchor = document.createElement('a'); anchor.href = url; anchor.download = 'humanizer-rewrite.txt'; anchor.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
});
window.addEventListener('pagehide', () => { if (activeJob) activeJob.cancel(); });
counts();
|