Files
smeta-web/static/batch2.html
T
anorandClaude Opus 4.6 5ebf9db332 feat: Batch V2 — Claude Code анализирует файлы и генерирует скрипт
Вместо GLM + шаблонного скрипта (V1), V2 использует Claude Code (1M контекст):
- Сэмплирует 15 файлов из набора (до 2000+), конвертирует xlsx→CSV
- Claude читает сэмплы + target, генерирует кастомный Python-скрипт
- Адаптируется к ЛЮБОЙ структуре файлов (не hardcoded формат)
- Пользователь подтверждает → скрипт выполняется на всех файлах

Новые файлы: batch_v2.py, static/batch2.html
Новые endpoints: /batch2, /api/batch-v2/{upload,analyze,run,status,download}
V1 (/batch) остаётся как fallback.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 23:14:50 +10:00

237 lines
12 KiB
HTML

<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Пакетная обработка V2 — Claude Code</title>
<style>
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; --green: #2d8a56; }
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; padding: 2rem; }
.container { max-width: 750px; margin: 0 auto; }
h1 { font-size: 1.3rem; margin-bottom: .3rem; }
.subtitle { color: var(--muted); font-size: .9rem; margin-bottom: 1.5rem; }
.badge { display: inline-block; background: var(--green); color: #fff; font-size: .7rem; padding: 2px 8px; border-radius: 12px; vertical-align: middle; margin-left: .5rem; }
.card { background: var(--card); border-radius: var(--radius); padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,.06); }
.card.hidden { display: none; }
label { display: block; font-weight: 600; margin-bottom: .4rem; font-size: .9rem; }
.hint { color: var(--muted); font-size: .8rem; margin-bottom: .6rem; }
input[type=file] { width: 100%; padding: .5rem; border: 1.5px dashed var(--border); border-radius: var(--radius); margin-bottom: 1rem; }
textarea { width: 100%; padding: .6rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-family: inherit; font-size: .9rem; resize: vertical; min-height: 80px; }
button { padding: .7rem 1.5rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
button:hover { background: #a83830; }
button:disabled { background: var(--border); cursor: not-allowed; }
.back { display: inline-block; margin-bottom: 1rem; color: var(--accent); text-decoration: none; font-size: .85rem; }
.progress { background: #ede5db; border-radius: 6px; height: 8px; margin: .5rem 0; }
.progress-bar { background: var(--accent); height: 100%; border-radius: 6px; transition: width .3s; }
.error-list { color: #c4463a; font-size: .8rem; margin-top: .5rem; max-height: 200px; overflow-y: auto; }
pre { background: #2c2c2c; color: #f5f0eb; padding: .8rem; border-radius: 6px; overflow-x: auto; font-size: .78rem; margin: .5rem 0; max-height: 400px; overflow-y: auto; white-space: pre-wrap; word-break: break-word; }
.log { background: #1a1a2e; color: #a0d2db; padding: .8rem; border-radius: 6px; font-size: .78rem; margin: .5rem 0; max-height: 300px; overflow-y: auto; font-family: monospace; white-space: pre-wrap; word-break: break-word; }
.info-row { display: flex; gap: 1rem; margin: .5rem 0; font-size: .85rem; color: var(--muted); }
.info-row span { background: #ede5db; padding: 3px 10px; border-radius: 6px; }
.spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: middle; margin-right: 6px; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>
</head>
<body>
<div class="container">
<a class="back" href="/">&#8592; Вернуться в чат</a>
<h1>Пакетная обработка смет <span class="badge">V2 Claude</span></h1>
<p class="subtitle">Claude Code читает ВСЕ файлы, понимает структуру, генерирует скрипт обработки</p>
<!-- Step 1: Upload -->
<div class="card" id="step-upload">
<label>1. Архив со сметами (.zip)</label>
<p class="hint">Все файлы локальных смет в одном архиве (до 2000 файлов)</p>
<input type="file" id="zip-file" accept=".zip">
<label>Сводный файл (.xlsx)</label>
<p class="hint">Файл, в который нужно внести данные (ССР, ведомость и т.д.)</p>
<input type="file" id="target-file" accept=".xlsx,.xls">
<label>Описание задачи</label>
<p class="hint">Опишите что именно нужно сделать — Claude прочитает файлы и разберётся</p>
<textarea id="task-desc" placeholder="Из каждого файла взять итоговые суммы по типам работ (строительные, монтажные, оборудование, прочие) и внести в соответствующие строки и колонки сводного файла. Значения в исходных файлах в рублях, в сводном — тыс.руб."></textarea>
<br><br>
<button id="btn-upload" onclick="uploadFiles()">Загрузить и конвертировать</button>
</div>
<!-- Step 2: Analysis -->
<div class="card hidden" id="step-analyze">
<label>2. Анализ Claude Code</label>
<div class="info-row" id="csv-info"></div>
<p style="margin:.5rem 0;font-size:.9rem"><span class="spinner" id="analyze-spinner"></span> <span id="analyze-status">Claude анализирует файлы...</span></p>
<div class="log" id="analyze-log"></div>
</div>
<!-- Step 3: Confirm script -->
<div class="card hidden" id="step-confirm">
<label>3. Сгенерированный скрипт</label>
<p class="hint">Проверьте скрипт и нажмите «Запустить»</p>
<pre id="script-code"></pre>
<div style="display:flex;gap:.5rem;margin-top:.8rem">
<button onclick="runScript()">Запустить обработку</button>
<button onclick="reanalyze()" style="background:var(--border);color:var(--text)">Переанализировать</button>
</div>
</div>
<!-- Step 4: Execution -->
<div class="card hidden" id="step-run">
<label>4. Выполнение</label>
<p id="run-status"></p>
<div class="progress"><div class="progress-bar" id="run-progress" style="width:0%"></div></div>
<p id="run-count" style="font-size:.85rem;color:var(--muted)"></p>
<div class="error-list" id="run-errors"></div>
<button id="btn-download" style="display:none" onclick="downloadResult()">Скачать результат</button>
</div>
</div>
<script>
const token = localStorage.getItem('token');
if (!token) window.location.href = '/';
const H = {'Authorization': 'Bearer ' + token};
let jobId = null;
function show(id) { document.getElementById(id).classList.remove('hidden'); }
function hide(id) { document.getElementById(id).classList.add('hidden'); }
async function uploadFiles() {
const zipFile = document.getElementById('zip-file').files[0];
const targetFile = document.getElementById('target-file').files[0];
const taskDesc = document.getElementById('task-desc').value;
if (!zipFile || !targetFile) { alert('Загрузите оба файла'); return; }
const btn = document.getElementById('btn-upload');
btn.disabled = true; btn.textContent = 'Загружаю...';
const fd = new FormData();
fd.append('zip_file', zipFile);
fd.append('target_file', targetFile);
fd.append('task_description', taskDesc || 'Перенести итоги из смет в сводный файл');
try {
const r = await fetch('/api/batch-v2/upload', {method: 'POST', headers: H, body: fd});
if (r.status === 401) { window.location.href = '/'; return; }
const data = await r.json();
jobId = data.job_id;
const info = data.csv_info;
document.getElementById('csv-info').innerHTML =
`<span>${data.total_files} xlsx всего</span>` +
`<span>${info.sample_count} CSV сэмплов</span>` +
`<span>~${Math.round(info.estimated_tokens/1000)}K токенов</span>`;
show('step-analyze');
startAnalysis();
} catch(e) { alert('Ошибка: ' + e.message); }
finally { btn.disabled = false; btn.textContent = 'Загрузить и конвертировать'; }
}
async function startAnalysis() {
const log = document.getElementById('analyze-log');
log.textContent = '';
try {
const r = await fetch('/api/batch-v2/analyze/' + jobId, {method: 'POST', headers: H});
const reader = r.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const {done, value} = await reader.read();
if (done) break;
buffer += decoder.decode(value, {stream: true});
const lines = buffer.split('\n');
buffer = lines.pop(); // keep incomplete line
let eventType = '';
for (const line of lines) {
if (line.startsWith('event: ')) { eventType = line.slice(7); continue; }
if (!line.startsWith('data: ')) continue;
try {
const d = JSON.parse(line.slice(6));
if (eventType === 'text') {
log.textContent += d.text;
log.scrollTop = log.scrollHeight;
} else if (eventType === 'tool') {
log.textContent += '\n[tool: ' + d.tool + ']\n';
log.scrollTop = log.scrollHeight;
} else if (eventType === 'done') {
document.getElementById('analyze-spinner').style.display = 'none';
if (d.script) {
document.getElementById('analyze-status').textContent = 'Анализ завершён';
document.getElementById('script-code').textContent = d.script;
show('step-confirm');
} else {
document.getElementById('analyze-status').textContent = 'Claude не сгенерировал скрипт';
document.getElementById('analyze-status').style.color = 'var(--accent)';
}
}
} catch(e) {}
}
}
} catch(e) {
document.getElementById('analyze-spinner').style.display = 'none';
document.getElementById('analyze-status').textContent = 'Ошибка: ' + e.message;
document.getElementById('analyze-status').style.color = 'var(--accent)';
}
}
async function reanalyze() {
hide('step-confirm');
document.getElementById('analyze-spinner').style.display = 'inline-block';
document.getElementById('analyze-status').textContent = 'Claude анализирует файлы...';
document.getElementById('analyze-status').style.color = '';
startAnalysis();
}
async function runScript() {
try {
const r = await fetch('/api/batch-v2/run/' + jobId, {method: 'POST', headers: H});
if (!r.ok) { alert('Ошибка запуска'); return; }
show('step-run');
pollStatus();
} catch(e) { alert('Ошибка: ' + e.message); }
}
async function pollStatus() {
const r = await fetch('/api/batch-v2/status/' + jobId, {headers: H});
const d = await r.json();
const pct = d.total > 0 ? (d.processed / d.total * 100) : 0;
document.getElementById('run-progress').style.width = pct + '%';
document.getElementById('run-count').textContent = d.processed + ' / ' + d.total + ' файлов';
if (d.status === 'running') {
document.getElementById('run-status').textContent = 'Обработка...';
setTimeout(pollStatus, 1500);
} else if (d.status === 'completed') {
document.getElementById('run-status').textContent = 'Готово! Обработано: ' + d.processed + ' из ' + d.total;
document.getElementById('run-status').style.color = 'var(--green)';
document.getElementById('btn-download').style.display = 'inline-block';
} else if (d.status === 'failed') {
document.getElementById('run-status').textContent = 'Ошибка выполнения';
document.getElementById('run-status').style.color = 'var(--accent)';
}
if (d.errors && d.errors.length > 0) {
document.getElementById('run-errors').innerHTML = '<b>Ошибки:</b><br>' + d.errors.map(e => '&bull; ' + e).join('<br>');
}
}
function downloadResult() {
fetch('/api/batch-v2/download/' + jobId, {headers: H})
.then(r => r.blob())
.then(b => {
const u = URL.createObjectURL(b);
const a = document.createElement('a');
a.href = u; a.download = 'result.xlsx'; a.click();
URL.revokeObjectURL(u);
});
}
</script>
</body>
</html>