Spaces:
Running
Running
File size: 6,657 Bytes
b89c431 | 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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | const http = require('http');
const fs = require('fs');
const BACKEND_PORT = process.env.PORT || 7861;
const CSS = `@media print { @page { size: A4; margin: 15mm 10mm; } body { -webkit-print-color-adjust: exact; } }
body { font-family: -apple-system, sans-serif; font-size: 14px; line-height: 1.6; max-width: 746px; margin: 0 auto; padding: 20px; }
h1,h2,h3 { font-weight: 600; margin: 16px 0 8px; }
pre { background: #f6f8fa; padding: 16px; border-radius: 6px; overflow-x: auto; border: 1px solid #e1e4e8; }
code { font-family: monospace; font-size: 13px; }
p { margin: 8px 0; } table { border-collapse: collapse; width: 100%; margin: 12px 0; }
th,td { border: 1px solid #dfe2e5; padding: 8px 12px; } th { background: #f1f3f4; }
.chat-container { display: flex; flex-direction: column; gap: 16px; }
.message-row { display: flex; gap: 10px; } .message-bubble { max-width: 85%; padding: 12px 16px; border-radius: 12px; }
.ai-bubble { background: #fff; border: 1px solid #eee; } .user-bubble { background: #e8f0fe; }
.avatar { width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; }`;
function E(s) { return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
function shikiWrap(token, color) {
return `<span style="color:${color}">${E(token)}</span>`;
}
function generateShikiCode(lines) {
return lines.map(line => {
const parts = [];
const tokens = line.split(/(\s+|[^a-zA-Z0-9_\s]+)/g);
for (const tok of tokens) {
if (!tok) continue;
if (/^\s+$/.test(tok)) { parts.push(tok); continue; }
let color = '#c9d1d9';
if (/^(const|let|var|function|return|if|else|for|async|await|import|from|export|class|extends|new|try|catch|throw|typeof|this|switch|case|break|continue|while|do|of|in|static|get|set|super|interface|type|void|null|undefined|true|false)$/.test(tok)) color = '#ff7b72';
else if (/^(console|log|error|fetch|Promise|Math|Date|JSON|Map|Set|Array|Object|String|Number|Error|setTimeout|clearTimeout|AbortController|AbortSignal|require|module|exports|process)$/.test(tok)) color = '#d2a8ff';
else if (/^\d+$/.test(tok)) color = '#79c0ff';
else if (/^[{}()\[\];,\.:=+\-*/<>!&|?%@~^'"`]+$/.test(tok)) color = '#c9d1d9';
else if (/^[A-Z]/.test(tok) && tok.length > 1) color = '#ffa657';
parts.push(shikiWrap(tok, color));
}
return parts.join('');
}).join('\n');
}
const CODE_LINES = [
'async function fetchData(url, options = {}) {',
' const controller = new AbortController();',
' const timeout = setTimeout(() => controller.abort(), 30000);',
' try {',
' const response = await fetch(url, {',
' ...options,',
' signal: controller.signal,',
" headers: { 'Content-Type': 'application/json' },",
' });',
' if (!response.ok) {',
' throw new Error(`HTTP ${response.status}: ${response.statusText}`);',
' }',
' const data = await response.json();',
" console.log('Data received:', data);",
' return data;',
' } catch (error) {',
" console.error('Fetch failed:', error.message);",
' throw error;',
' } finally {',
' clearTimeout(timeout);',
' }',
'}',
];
const TEXT = '<p>This is a typical AI response explaining a concept with some details and examples that users commonly see in chat conversations.</p>';
function buildHtml(targetSizeMB) {
const shikiCode = generateShikiCode(CODE_LINES);
const codeBlock = `<pre data-language="javascript"><code class="language-javascript">${shikiCode}</code></pre>`;
const codeBlockSize = Buffer.byteLength(codeBlock, 'utf8');
const textBlockSize = Buffer.byteLength(TEXT, 'utf8');
const overhead = 2048;
const targetBytes = targetSizeMB * 1024 * 1024 - overhead;
let html = `<!DOCTYPE html><html><head><meta charset="UTF-8"><style>${CSS}</style></head><body><div class="chat-container">`;
const codeIterations = Math.ceil((targetBytes * 0.5) / codeBlockSize);
const textIterations = Math.ceil((targetBytes * 0.5) / textBlockSize);
let i = 0, j = 0;
while (i < codeIterations || j < textIterations) {
if (i < codeIterations) {
html += `<div class="message-row"><div class="avatar">🤖</div><div class="message-bubble ai-bubble">${codeBlock}</div></div>`;
i++;
}
if (j < textIterations) {
html += `<div class="message-row"><div class="avatar">👤</div><div class="message-bubble user-bubble">${TEXT}</div></div>`;
j++;
}
}
html += '</div></body></html>';
return html;
}
async function sendPdfRequest(html) {
const payload = JSON.stringify({
html, codeTheme: 'github', showWatermark: false,
imageCount: 0, totalImageSizeMB: 0,
platform: 'Benchmark', language: 'en-US', extensionVersion: '2.0.2',
exportCount: 0, exportPdf: 0, exportMd: 0, exportTxt: 0,
exportDocx: 0, exportJson: 0, exportClipboard: 0, exportNotion: 0,
});
return new Promise((resolve, reject) => {
const startTime = Date.now();
const req = http.request({
hostname: 'localhost', port: BACKEND_PORT, path: '/api/generate_pdf',
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) },
timeout: 1800000, // 30 min
}, (res) => {
const chunks = [];
res.on('data', (chunk) => chunks.push(chunk));
res.on('end', () => {
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
if (res.statusCode === 200) {
resolve({ ok: true, elapsed, pdfSizeMB: (Buffer.concat(chunks).length / 1024 / 1024).toFixed(2) });
} else {
resolve({ ok: false, elapsed, status: res.statusCode, error: Buffer.concat(chunks).toString() });
}
});
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(); reject(new Error('HTTP timeout')); });
req.write(payload);
req.end();
});
}
async function main() {
const size = parseFloat(process.argv[2] || '4.92');
const html = buildHtml(size);
const actualSizeMB = (Buffer.byteLength(html, 'utf8') / 1024 / 1024).toFixed(2);
console.log(`Testing ${size} MB target, actual ${actualSizeMB} MB HTML...`);
console.log(`Start: ${new Date().toISOString()}`);
try {
const result = await sendPdfRequest(html);
console.log(`End: ${new Date().toISOString()}`);
if (result.ok) {
console.log(`SUCCESS in ${result.elapsed}s, PDF: ${result.pdfSizeMB} MB`);
} else {
console.log(`FAIL: HTTP ${result.status}, ${result.elapsed}s`);
console.log(result.error);
}
} catch (err) {
console.error(`ERROR: ${err.message}`);
}
}
main();
|