feat: batch V2 — показываем паттерны вместо скрипта + ссылка с главной

- Claude генерирует batch_summary.json с найденными паттернами
- UI показывает сметчику: лист, шифр, паттерны итогов, маппинг столбцов
- Скрипт скрыт в <details> для разработчиков
- Кнопка «Пакетная V2» на главной странице чата

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-26 01:47:49 +10:00
co-authored by Claude Opus 4.6
parent 5ebf9db332
commit d6a0bdc7bf
4 changed files with 101 additions and 10 deletions
+44 -3
View File
@@ -196,7 +196,41 @@ NOTE: In the script, use the `target_file` variable (not a hardcoded path).
1. Read the sample CSV files in /data/sample_csv/ — understand their structure 1. Read the sample CSV files in /data/sample_csv/ — understand their structure
2. Read the target CSV files in /data/target_csv/ — understand where data goes 2. Read the target CSV files in /data/target_csv/ — understand where data goes
3. Figure out: what to extract from each source, how to match to target rows 3. Figure out: what to extract from each source, how to match to target rows
4. Write a COMPLETE Python script to /data/batch_script.py 4. Write TWO files:
### File 1: /data/batch_summary.json — human-readable summary for the user
JSON with these fields (in Russian):
```json
{{
"description": "Краткое описание что будет сделано",
"source_patterns": {{
"sheet": "на каком листе искать данные",
"id_field": "где шифр/название сметы (например: имя файла, ячейка B5)",
"totals": {{
"строительные работы": "паттерн поиска (например: ВСЕГО строительные работы)",
"монтажные работы": "паттерн поиска",
"оборудование": "паттерн поиска",
"прочие затраты": "паттерн поиска"
}},
"value_column": "в каком столбце значения (например: A или H)",
"units": "рубли или тыс.руб"
}},
"target_mapping": {{
"sheet": "на какой лист сводного файла записывать",
"match_column": "столбец с шифрами для сопоставления (например: B)",
"value_columns": {{
"строительные работы": "столбец (например: D)",
"монтажные работы": "столбец (например: E)",
"оборудование": "столбец (например: F)",
"прочие затраты": "столбец (например: G)"
}},
"units": "тыс.руб"
}},
"conversion": "делить на 1000 (руб → тыс.руб)" или "без конвертации"
}}
```
### File 2: /data/batch_script.py — Python script
## CRITICAL: The script will run on ALL {total_xlsx_count} files, not just samples! ## CRITICAL: The script will run on ALL {total_xlsx_count} files, not just samples!
The script must handle any file with the same general structure as the samples. The script must handle any file with the same general structure as the samples.
@@ -303,12 +337,19 @@ async def run_claude_analysis(
elif etype == "result": elif etype == "result":
got_result = True got_result = True
script_path = job_dir / "batch_script.py" script_path = job_dir / "batch_script.py"
summary_path = job_dir / "batch_summary.json"
summary = {}
if summary_path.exists():
try:
summary = json.loads(summary_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
pass
if script_path.exists(): if script_path.exists():
script = script_path.read_text(encoding="utf-8") script = script_path.read_text(encoding="utf-8")
yield {"type": "done", "script": script} yield {"type": "done", "script": script, "summary": summary}
else: else:
result_text = event.get("result", "") result_text = event.get("result", "")
yield {"type": "done", "script": "", "result": result_text} yield {"type": "done", "script": "", "result": result_text, "summary": summary}
finally: finally:
if proc.returncode is None: if proc.returncode is None:
+3 -2
View File
@@ -465,13 +465,14 @@ async def batch_v2_analyze(job_id: str, request: Request):
yield f"event: tool\ndata: {json.dumps({'tool': event['tool']}, ensure_ascii=False)}\n\n" yield f"event: tool\ndata: {json.dumps({'tool': event['tool']}, ensure_ascii=False)}\n\n"
elif etype == "done": elif etype == "done":
script = event.get("script", "") script = event.get("script", "")
summary = event.get("summary", {})
if script: if script:
job["analysis"] = {"python_script": script} job["analysis"] = {"python_script": script, "summary": summary}
job["status"] = "analyzed" job["status"] = "analyzed"
else: else:
job["analysis"] = {"error": "Claude did not generate script", "result": event.get("result", "")} job["analysis"] = {"error": "Claude did not generate script", "result": event.get("result", "")}
job["status"] = "analysis_failed" job["status"] = "analysis_failed"
yield f"event: done\ndata: {json.dumps({'script': script, 'status': job['status']}, ensure_ascii=False)}\n\n" yield f"event: done\ndata: {json.dumps({'script': script, 'summary': summary, 'status': job['status']}, ensure_ascii=False)}\n\n"
return StreamingResponse( return StreamingResponse(
event_stream(), event_stream(),
+52 -4
View File
@@ -64,11 +64,14 @@ pre { background: #2c2c2c; color: #f5f0eb; padding: .8rem; border-radius: 6px; o
<div class="log" id="analyze-log"></div> <div class="log" id="analyze-log"></div>
</div> </div>
<!-- Step 3: Confirm script --> <!-- Step 3: Confirm -->
<div class="card hidden" id="step-confirm"> <div class="card hidden" id="step-confirm">
<label>3. Сгенерированный скрипт</label> <label>3. Проверьте найденные параметры</label>
<p class="hint">Проверьте скрипт и нажмите «Запустить»</p> <div id="summary-view" style="font-size:.9rem;line-height:1.6"></div>
<pre id="script-code"></pre> <details style="margin-top:.8rem">
<summary style="cursor:pointer;color:var(--muted);font-size:.8rem">Показать скрипт (для разработчиков)</summary>
<pre id="script-code"></pre>
</details>
<div style="display:flex;gap:.5rem;margin-top:.8rem"> <div style="display:flex;gap:.5rem;margin-top:.8rem">
<button onclick="runScript()">Запустить обработку</button> <button onclick="runScript()">Запустить обработку</button>
<button onclick="reanalyze()" style="background:var(--border);color:var(--text)">Переанализировать</button> <button onclick="reanalyze()" style="background:var(--border);color:var(--text)">Переанализировать</button>
@@ -163,6 +166,7 @@ async function startAnalysis() {
if (d.script) { if (d.script) {
document.getElementById('analyze-status').textContent = 'Анализ завершён'; document.getElementById('analyze-status').textContent = 'Анализ завершён';
document.getElementById('script-code').textContent = d.script; document.getElementById('script-code').textContent = d.script;
renderSummary(d.summary);
show('step-confirm'); show('step-confirm');
} else { } else {
document.getElementById('analyze-status').textContent = 'Claude не сгенерировал скрипт'; document.getElementById('analyze-status').textContent = 'Claude не сгенерировал скрипт';
@@ -221,6 +225,50 @@ async function pollStatus() {
} }
} }
function renderSummary(s) {
const el = document.getElementById('summary-view');
if (!s || !s.source_patterns) {
el.innerHTML = '<p style="color:var(--muted)">Параметры не распознаны — проверьте скрипт вручную</p>';
return;
}
const src = s.source_patterns || {};
const tgt = s.target_mapping || {};
let html = '';
if (s.description) html += `<p><b>${s.description}</b></p>`;
html += '<table style="width:100%;border-collapse:collapse;margin:.5rem 0;font-size:.85rem">';
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Исходные файлы</td></tr>';
if (src.sheet) html += row('Лист', src.sheet);
if (src.id_field) html += row('Шифр/название', src.id_field);
if (src.value_column) html += row('Столбец значений', src.value_column);
if (src.units) html += row('Единицы', src.units);
if (src.totals) {
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Паттерны поиска итогов</td></tr>';
for (const [k, v] of Object.entries(src.totals)) {
html += row(k, '<code>' + v + '</code>');
}
}
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Сводный файл</td></tr>';
if (tgt.sheet) html += row('Лист', tgt.sheet);
if (tgt.match_column) html += row('Столбец сопоставления', tgt.match_column);
if (tgt.value_columns) {
for (const [k, v] of Object.entries(tgt.value_columns)) {
html += row(k + ' →', 'столбец ' + v);
}
}
if (tgt.units) html += row('Единицы', tgt.units);
if (s.conversion) html += row('Конвертация', s.conversion);
html += '</table>';
el.innerHTML = html;
function row(label, value) {
return `<tr><td style="padding:4px 6px;border-bottom:1px solid #eee;color:var(--muted);width:40%">${label}</td><td style="padding:4px 6px;border-bottom:1px solid #eee">${value}</td></tr>`;
}
}
function downloadResult() { function downloadResult() {
fetch('/api/batch-v2/download/' + jobId, {headers: H}) fetch('/api/batch-v2/download/' + jobId, {headers: H})
.then(r => r.blob()) .then(r => r.blob())
+2 -1
View File
@@ -117,7 +117,8 @@ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Robo
<div id="header"> <div id="header">
<h1>Сметный ИИ-ассистент</h1> <h1>Сметный ИИ-ассистент</h1>
<div class="header-actions"> <div class="header-actions">
<button onclick="window.open('/batch','_blank')">Пакетная</button> <button onclick="window.open('/batch2','_blank')">Пакетная V2</button>
<button onclick="window.open('/batch','_blank')">Пакетная V1</button>
<button onclick="showSessions()">История</button> <button onclick="showSessions()">История</button>
<button onclick="resetSession()">Новый диалог</button> <button onclick="resetSession()">Новый диалог</button>
<button onclick="listFiles()">Файлы</button> <button onclick="listFiles()">Файлы</button>