Files
ppq-analyzer/ppq-analyzer.html
T
ai-bot f12bc5c162 Update ppq-analyzer.html
add sortable tables and English interface
2026-09-25 10:20:59 +00:00

605 lines
23 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PPQ Cost Analyzer</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container { max-width: 1200px; margin: 0 auto; }
header { text-align: center; color: white; margin-bottom: 30px; }
header h1 { font-size: 2rem; margin-bottom: 10px; }
header p { opacity: 0.9; }
.upload-section {
background: white;
border-radius: 12px;
padding: 40px;
text-align: center;
margin-bottom: 30px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}
.upload-area {
border: 3px dashed #ccc;
border-radius: 8px;
padding: 60px 20px;
cursor: pointer;
transition: all 0.3s;
}
.upload-area:hover, .upload-area.dragover {
border-color: #6d4aff;
background: #f0ebff;
}
.file-info {
display: none;
margin-top: 20px;
padding: 15px;
background: #e8f5e9;
border-radius: 8px;
color: #2e7d32;
}
button.analyze-btn {
background: #6d4aff;
color: white;
border: none;
padding: 15px 40px;
font-size: 1.1rem;
border-radius: 8px;
cursor: pointer;
margin-top: 20px;
display: none;
}
button.analyze-btn:hover { background: #5a3fd6; }
button.analyze-btn:disabled { background: #ccc; cursor: not-allowed; }
.report-section {
background: white;
border-radius: 12px;
padding: 40px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
display: none;
}
.report-section.active { display: block; }
h2 {
color: #6d4aff;
margin: 30px 0 20px 0;
padding-bottom: 10px;
border-bottom: 2px solid #eee;
}
h2:first-of-type { margin-top: 0; }
.table-wrapper {
width: 100%;
overflow-x: auto;
margin: 20px 0;
border: 1px solid #eee;
border-radius: 8px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.95rem;
}
th, td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid #ddd;
white-space: nowrap;
}
th {
background: #f8f5ff;
color: #6d4aff;
font-weight: 600;
}
th:last-child, td:last-child { border-right: none; }
tbody tr:hover { background: #faf9fc; }
.sort-button {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 0;
border: 0;
background: transparent;
color: inherit;
font: inherit;
font-weight: inherit;
cursor: pointer;
text-align: left;
}
.sort-button:hover { color: #4e30c9; }
.sort-button:focus-visible {
outline: 2px solid #6d4aff;
outline-offset: 2px;
border-radius: 3px;
}
.sort-indicator {
min-width: 1.1em;
text-align: center;
font-size: 0.85rem;
opacity: 0.45;
}
.sort-button[aria-sort="ascending"] .sort-indicator,
.sort-button[aria-sort="descending"] .sort-indicator { opacity: 1; }
.metric-card {
display: inline-block;
background: linear-gradient(135deg, #6d4aff 0%, #8b5cf6 100%);
color: white;
padding: 20px 30px;
border-radius: 8px;
margin: 10px;
min-width: 180px;
box-shadow: 0 4px 15px rgba(109,74,255,0.3);
}
.metric-value { font-size: 1.8rem; font-weight: bold; margin-bottom: 5px; }
.metric-label { opacity: 0.9; font-size: 0.9rem; }
.finding-box, .warning-box, .success-box {
padding: 15px 20px;
margin: 20px 0;
border-radius: 4px;
border-left: 4px solid;
}
.finding-box { background: #fff3cd; border-color: #ffc107; }
.warning-box { background: #f8d7da; border-color: #dc3545; }
.success-box { background: #d4edda; border-color: #28a745; }
.debug-log {
background: #1a1a2e;
color: #0f0;
padding: 15px;
border-radius: 8px;
margin: 20px 0;
font-family: monospace;
font-size: 0.85rem;
max-height: 200px;
overflow-y: auto;
display: none;
}
.privacy-note {
background: rgba(255,255,255,0.15);
color: white;
padding: 15px;
border-radius: 8px;
text-align: center;
margin-top: 20px;
font-size: 0.9rem;
}
.status-msg {
padding: 10px;
margin: 10px 0;
border-radius: 8px;
display: none;
}
.status-error { background: #f8d7da; color: #721c24; }
.status-success { background: #d4edda; color: #155724; }
</style>
</head>
<body>
<div class="container">
<header>
<h1>📊 PPQ Cost Analyzer</h1>
<p>Drag &amp; drop a CSV file here — all data stays local!</p>
</header>
<section class="upload-section" id="uploadSection">
<div class="upload-area" id="uploadArea">
<div style="font-size: 3rem; margin-bottom: 15px;">📄</div>
<div style="font-size: 1.2rem; margin-bottom: 10px;"><strong>Drag &amp; drop a CSV file here</strong></div>
<div style="color: #666;">or click to select a file</div>
</div>
<input type="file" id="fileInput" accept=".csv" style="display:none">
<div class="status-msg" id="statusMsg"></div>
<div class="file-info" id="fileInfo"></div>
<button class="analyze-btn" id="analyzeBtn">Analyze data</button>
<div class="debug-log" id="debugLog">
<strong>Debug:</strong><br>
</div>
</section>
<section class="report-section" id="reportSection">
<div class="privacy-note">
🔒 All data is processed locally in your browser. Nothing is uploaded.
</div>
<h2>📊 Summary</h2>
<div id="summaryMetrics"></div>
<h2>💰 Cost by model</h2>
<div id="modelTableContainer"></div>
<h2>📅 Daily breakdown</h2>
<div id="dailyTableContainer"></div>
<h2>⚠️ Anomalies</h2>
<div id="anomalies"></div>
</section>
</div>
<script>
function log(msg) {
const debugLog = document.getElementById('debugLog');
debugLog.style.display = 'block';
debugLog.innerHTML += `[${new Date().toLocaleTimeString()}] ${msg}<br>`;
debugLog.scrollTop = debugLog.scrollHeight;
console.log('[PPQ Analyzer]', msg);
}
function showStatus(msg, isError = false) {
const statusEl = document.getElementById('statusMsg');
statusEl.style.display = 'block';
statusEl.className = 'status-msg ' + (isError ? 'status-error' : 'status-success');
statusEl.textContent = msg;
}
let csvData = [];
let rawData = '';
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const fileInfo = document.getElementById('fileInfo');
const analyzeBtn = document.getElementById('analyzeBtn');
const reportSection = document.getElementById('reportSection');
const uploadSection = document.getElementById('uploadSection');
uploadArea.addEventListener('click', () => fileInput.click());
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
uploadArea.classList.add('dragover');
});
uploadArea.addEventListener('dragleave', (e) => {
e.preventDefault();
uploadArea.classList.remove('dragover');
});
uploadArea.addEventListener('drop', (e) => {
e.preventDefault();
uploadArea.classList.remove('dragover');
if (e.dataTransfer.files.length > 0) handleFile(e.dataTransfer.files[0]);
});
fileInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) handleFile(e.target.files[0]);
});
analyzeBtn.addEventListener('click', generateReport);
function handleFile(file) {
if (!file.name.toLowerCase().endsWith('.csv')) {
showStatus('Error: Please upload a .csv file.', true);
return;
}
const reader = new FileReader();
reader.onload = (event) => {
rawData = event.target.result;
fileInfo.style.display = 'block';
fileInfo.innerHTML = `✅ <strong>${escapeHtml(file.name)}</strong><br>Size: ${formatSize(file.size)} | Ready to analyze`;
analyzeBtn.style.display = 'inline-block';
analyzeBtn.disabled = false;
showStatus('File loaded! Click "Analyze data" to start.', false);
};
reader.onerror = () => showStatus('Error reading file.', true);
reader.readAsText(file, 'UTF-8');
}
function parseCSV(csvText) {
const lines = csvText.trim().split(/\r?\n/).filter(line => line.trim());
if (lines.length < 2) return [];
const headers = parseCSVLine(lines[0]);
const data = [];
let errors = 0;
for (let i = 1; i < lines.length; i++) {
const line = lines[i];
if (line.includes('Total Records') || line.trim() === '') continue;
const values = parseCSVLine(line);
if (values.length !== headers.length) {
errors++;
continue;
}
const row = {};
headers.forEach((header, idx) => {
let val = values[idx];
if (header.includes('Tokens') || header === 'Price (USD)') {
val = parseFloat(val) || 0;
}
row[header] = val;
});
data.push(row);
}
log(`Parsed ${data.length} rows${errors ? `, ${errors} rows skipped` : ''}`);
return data;
}
function parseCSVLine(line) {
const values = [];
let inQuotes = false;
let current = '';
for (let i = 0; i < line.length; i++) {
const char = line[i];
const next = line[i + 1];
if (char === '"' && inQuotes && next === '"') {
current += '"';
i++;
} else if (char === '"') {
inQuotes = !inQuotes;
} else if (char === ',' && !inQuotes) {
values.push(current.trim());
current = '';
} else {
current += char;
}
}
values.push(current.trim());
return values;
}
function formatSize(bytes) {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
}
function formatNumber(num) {
return Math.floor(num).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
}
function escapeHtml(value) {
return String(value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
function generateReport() {
if (!rawData) {
showStatus('No data found. Please upload a CSV file first.', true);
return;
}
csvData = parseCSV(rawData);
if (csvData.length === 0) {
showStatus('Could not read any data from the file.', true);
return;
}
const stats = calculateStats(csvData);
renderSummary(stats);
renderModelTable(stats.models);
renderDailyTable(stats.daily);
renderAnomalies(csvData);
uploadSection.style.display = 'none';
reportSection.classList.add('active');
window.scrollTo(0, 0);
}
function calculateStats(data) {
const models = {};
const daily = {};
data.forEach(row => {
const model = row.Model || 'unknown';
if (!models[model]) {
models[model] = { count: 0, totalCost: 0, totalInput: 0, totalOutput: 0 };
}
models[model].count++;
models[model].totalCost += row['Price (USD)'] || 0;
models[model].totalInput += row['Input Tokens'] || 0;
models[model].totalOutput += row['Output Tokens'] || 0;
const date = row.Date || 'unknown';
if (!daily[date]) daily[date] = { cost: 0, count: 0 };
daily[date].cost += row['Price (USD)'] || 0;
daily[date].count++;
});
return {
totalCost: data.reduce((sum, r) => sum + (r['Price (USD)'] || 0), 0),
totalRequests: data.length,
totalInput: data.reduce((sum, r) => sum + (r['Input Tokens'] || 0), 0),
totalOutput: data.reduce((sum, r) => sum + (r['Output Tokens'] || 0), 0),
uniqueDates: new Set(data.map(r => r.Date)).size,
models,
daily
};
}
function renderSummary(stats) {
const container = document.getElementById('summaryMetrics');
const averageDailyCost = stats.uniqueDates > 0 ? stats.totalCost / stats.uniqueDates : 0;
container.innerHTML = `
<div class="metric-card">
<div class="metric-value">$${stats.totalCost.toFixed(2)}</div>
<div class="metric-label">Total cost</div>
</div>
<div class="metric-card">
<div class="metric-value">${formatNumber(stats.totalRequests)}</div>
<div class="metric-label">Requests</div>
</div>
<div class="metric-card">
<div class="metric-value">${formatNumber(Math.round(stats.totalInput / 1000000))}M</div>
<div class="metric-label">Input tokens</div>
</div>
<div class="metric-card">
<div class="metric-value">$${averageDailyCost.toFixed(2)}</div>
<div class="metric-label">Per day</div>
</div>
`;
}
function sortRows(rows, key, type, direction) {
const multiplier = direction === 'asc' ? 1 : -1;
return [...rows].sort((a, b) => {
let result = 0;
if (type === 'number') {
result = Number(a[key]) - Number(b[key]);
} else {
result = String(a[key]).localeCompare(String(b[key]), undefined, { numeric: true, sensitivity: 'base' });
}
return result * multiplier;
});
}
function renderSortableTable(containerId, tableId, columns, rows, defaultSort) {
const container = document.getElementById(containerId);
let sortKey = defaultSort.key;
let sortDirection = defaultSort.direction;
function render() {
const sortedRows = sortRows(rows, sortKey, columns.find(c => c.key === sortKey).type, sortDirection);
let html = `<div class="table-wrapper"><table id="${tableId}"><thead><tr>`;
columns.forEach(column => {
const isActive = sortKey === column.key;
const ariaSort = isActive ? (sortDirection === 'asc' ? 'ascending' : 'descending') : 'none';
const indicator = isActive ? (sortDirection === 'asc' ? '▲' : '▼') : '↕';
html += `
<th scope="col">
<button class="sort-button" type="button" data-sort-key="${escapeHtml(column.key)}" aria-sort="${ariaSort}">
<span>${escapeHtml(column.label)}</span>
<span class="sort-indicator" aria-hidden="true">${indicator}</span>
</button>
</th>`;
});
html += '</tr></thead><tbody>';
sortedRows.forEach(row => {
html += '<tr>';
columns.forEach(column => {
html += `<td>${column.render(row)}</td>`;
});
html += '</tr>';
});
html += '</tbody></table></div>';
container.innerHTML = html;
container.querySelectorAll('.sort-button').forEach(button => {
button.addEventListener('click', () => {
const clickedKey = button.dataset.sortKey;
if (clickedKey === sortKey) {
sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
} else {
sortKey = clickedKey;
sortDirection = 'asc';
}
render();
});
});
}
render();
}
function renderModelTable(models) {
const rows = Object.entries(models).map(([name, stats]) => ({
name,
requests: stats.count,
total: stats.totalCost,
average: stats.count > 0 ? stats.totalCost / stats.count : 0
}));
renderSortableTable('modelTableContainer', 'modelTable', [
{ key: 'name', label: 'Model', type: 'text', render: row => `<strong>${escapeHtml(row.name)}</strong>` },
{ key: 'requests', label: 'Requests', type: 'number', render: row => formatNumber(row.requests) },
{ key: 'total', label: 'Total ($)', type: 'number', render: row => `$${row.total.toFixed(2)}` },
{ key: 'average', label: 'Average ($)', type: 'number', render: row => `$${row.average.toFixed(4)}` }
], rows, { key: 'total', direction: 'desc' });
}
function renderDailyTable(daily) {
const rows = Object.entries(daily).map(([date, stats]) => ({
date,
cost: stats.cost,
requests: stats.count
}));
renderSortableTable('dailyTableContainer', 'dailyTable', [
{ key: 'date', label: 'Date', type: 'text', render: row => escapeHtml(row.date) },
{ key: 'cost', label: 'Cost ($)', type: 'number', render: row => `$${row.cost.toFixed(2)}` },
{ key: 'requests', label: 'Requests', type: 'number', render: row => formatNumber(row.requests) }
], rows, { key: 'date', direction: 'asc' });
}
function renderAnomalies(data) {
const anomaliesContainer = document.getElementById('anomalies');
const boxes = [];
const free = data.filter(r => (r['Price (USD)'] || 0) === 0);
if (free.length > 0) {
boxes.push({
type: 'success-box',
title: `${free.length} free requests`,
items: free.slice(0, 5).map(r => `${r.Model} (${formatNumber(r['Input Tokens'])} tokens)`)
});
}
const big = data.filter(r => (r['Input Tokens'] || 0) > 100000);
if (big.length > 0) {
boxes.push({
type: 'warning-box',
title: `${big.length} large contexts (>100k input tokens)`,
items: [...big]
.sort((a, b) => (b['Input Tokens'] || 0) - (a['Input Tokens'] || 0))
.slice(0, 5)
.map(r => `${r.Model}: ${formatNumber(r['Input Tokens'])} tokens, $${(r['Price (USD)'] || 0).toFixed(2)}`)
});
}
const topCosts = [...data]
.sort((a, b) => (b['Price (USD)'] || 0) - (a['Price (USD)'] || 0))
.slice(0, 3);
boxes.push({
type: 'finding-box',
title: 'Top 3 most expensive individual requests',
items: topCosts.map(r => `${r.Model} on ${r.Date} at ${r.Time}: $${(r['Price (USD)'] || 0).toFixed(2)}`)
});
const empty = data.filter(r => (r['Input Tokens'] || 0) === 0 || (r['Output Tokens'] || 0) === 0);
if (empty.length > 0) {
boxes.push({
type: 'warning-box',
title: `${empty.length} requests with 0 tokens`,
items: empty.slice(0, 5).map(r => `${r.Model} on ${r.Date} at ${r.Time}`)
});
}
if (boxes.length === 0) {
anomaliesContainer.innerHTML = '<div class="success-box">No anomalies found ✨</div>';
return;
}
let html = '';
boxes.forEach(box => {
html += `<div class="${box.type}">
<h3>${escapeHtml(box.title)}</h3>
<ul style="margin: 10px 0; padding-left: 20px;">
${box.items.map(item => `<li>${escapeHtml(item)}</li>`).join('')}
</ul>
</div>`;
});
anomaliesContainer.innerHTML = html;
}
</script>
</body>
</html>