fix: XML-парсер для реальных смет + smart detector + тесты
XML reader fixes: - inlineStr, row positioning, column refs, rels namespace - Анализ: head + tail (не только первые 30 строк) - max_rows=999 для полного чтения смет Выводы по реальным файлам (Строительный Эксперт): - Итоги в столбце A, подписи в H (не наоборот) - Шифр в имени файла, не в ячейке - Сводный ССР не содержит шифров ЛС — только разделы - Batch работает для стандартных файлов (тест 20/20) - Для реальных файлов нужен Claude Code или доработка Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -127,21 +127,43 @@ def extract_zip(zip_path: str, dest_dir: str) -> list[str]:
|
||||
|
||||
async def analyze_structure(sample_files: list[str], target_file: str, task_description: str) -> dict:
|
||||
"""Use LLM to analyze file structure and generate processing script."""
|
||||
# Read samples
|
||||
# Read samples — head + tail to see structure AND totals
|
||||
samples = []
|
||||
for f in sample_files[:3]:
|
||||
data = read_xlsx_xml(f, max_rows=30)
|
||||
samples.append({
|
||||
'filename': Path(f).name,
|
||||
'sheets': {k: v[:15] for k, v in data.items() if k != '_error'},
|
||||
})
|
||||
data = read_xlsx_xml(f, max_rows=999)
|
||||
sample = {'filename': Path(f).name, 'sheets': {}}
|
||||
for k, v in data.items():
|
||||
if k == '_error':
|
||||
continue
|
||||
head = v[:15]
|
||||
tail = v[-50:] if len(v) > 50 else v[15:]
|
||||
# Compact: only non-empty rows
|
||||
head_compact = [[j, row[j]] for row in head for j in range(len(row)) if row[j]]
|
||||
tail_compact = []
|
||||
for i, row in enumerate(tail):
|
||||
row_idx = len(v) - len(tail) + i
|
||||
cells = [[j, row[j]] for j in range(len(row)) if row[j]]
|
||||
if cells:
|
||||
tail_compact.append({'row': row_idx, 'cells': cells[:6]})
|
||||
sample['sheets'][k] = {
|
||||
'total_rows': len(v),
|
||||
'head': head_compact[:30],
|
||||
'tail': tail_compact[:30],
|
||||
}
|
||||
samples.append(sample)
|
||||
|
||||
# Read target structure
|
||||
target_data = read_xlsx_xml(target_file, max_rows=40)
|
||||
target_info = {
|
||||
'filename': Path(target_file).name,
|
||||
'sheets': {k: v[:20] for k, v in target_data.items() if k != '_error'},
|
||||
}
|
||||
target_data = read_xlsx_xml(target_file, max_rows=50)
|
||||
target_info = {'filename': Path(target_file).name, 'sheets': {}}
|
||||
for k, v in target_data.items():
|
||||
if k == '_error':
|
||||
continue
|
||||
compact = []
|
||||
for i, row in enumerate(v[:30]):
|
||||
cells = [[j, row[j]] for j in range(len(row)) if row[j]]
|
||||
if cells:
|
||||
compact.append({'row': i, 'cells': cells[:8]})
|
||||
target_info['sheets'][k] = {'total_rows': len(v), 'rows': compact}
|
||||
|
||||
prompt = f"""Ты — эксперт по автоматизации сметного дела.
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Test batch with real smeta files using smart detection."""
|
||||
import sys, re, shutil
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
from batch import read_xlsx_xml
|
||||
import openpyxl
|
||||
|
||||
SOURCE_DIR = "/tmp/real_batch/source"
|
||||
TARGET_ORIG = "/tmp/Раздел ПД N 9 Том 9.1 12.0866-СМ.ССР.xlsx"
|
||||
TARGET_FILE = "/tmp/real_batch/result_real.xlsx"
|
||||
|
||||
# Copy target
|
||||
shutil.copy2(TARGET_ORIG, TARGET_FILE)
|
||||
|
||||
# Get source files
|
||||
source_files = list(Path(SOURCE_DIR).rglob("*.xlsx"))
|
||||
print("Source files:", len(source_files))
|
||||
|
||||
# Open target
|
||||
wb = openpyxl.load_workbook(TARGET_FILE)
|
||||
ws = wb["ССРСС-1 ТУЦ"] if "ССРСС-1 ТУЦ" in wb.sheetnames else wb.active
|
||||
print("Target sheet:", ws.title)
|
||||
|
||||
# Build code → row mapping
|
||||
code_to_row = {}
|
||||
for r in range(1, ws.max_row + 1):
|
||||
v = ws.cell(r, 2).value # column B
|
||||
if v and str(v).startswith("ЛС-"):
|
||||
code_to_row[str(v).strip()] = r
|
||||
print("Target codes:", list(code_to_row.keys())[:5], "...")
|
||||
|
||||
# Process each source file
|
||||
processed = 0
|
||||
errors = []
|
||||
|
||||
KEYWORDS = {
|
||||
"строительные": "ВСЕГО строительные работы",
|
||||
"монтажные": "ВСЕГО монтажные работы",
|
||||
"оборудование": "ВСЕГО оборудование",
|
||||
"прочие": "ВСЕГО прочие затраты",
|
||||
}
|
||||
TARGET_COLS = {"строительные": 4, "монтажные": 5, "оборудование": 6, "прочие": 7} # D,E,F,G
|
||||
|
||||
for f in source_files:
|
||||
# Extract code from filename
|
||||
m = re.match(r"(ЛС-\d{2}-\d{2}-\d+-\d{2}-\d{2})", f.name)
|
||||
if not m:
|
||||
errors.append("%s: no code in filename" % f.name)
|
||||
continue
|
||||
code = m.group(1)
|
||||
|
||||
if code not in code_to_row:
|
||||
errors.append("%s: code %s not in target" % (f.name, code))
|
||||
continue
|
||||
|
||||
target_row = code_to_row[code]
|
||||
|
||||
# Read file
|
||||
data = read_xlsx_xml(str(f), max_rows=999)
|
||||
if not data:
|
||||
errors.append("%s: can't read" % f.name)
|
||||
continue
|
||||
|
||||
rows = list(data.values())[0]
|
||||
|
||||
# Find totals by keywords (search from end)
|
||||
for name, kw in KEYWORDS.items():
|
||||
for i in range(len(rows) - 1, max(0, len(rows) - 100), -1):
|
||||
found = False
|
||||
for j in range(len(rows[i])):
|
||||
v = str(rows[i][j]) if rows[i][j] else ""
|
||||
if kw.lower() in v.lower():
|
||||
# Find numeric value on same row
|
||||
for vj in range(len(rows[i])):
|
||||
val = rows[i][vj]
|
||||
if val and vj != j:
|
||||
try:
|
||||
num = float(str(val).replace(",", ".").replace(" ", ""))
|
||||
# Convert from rubles to thousands
|
||||
num_tys = round(num / 1000, 2)
|
||||
ws.cell(target_row, TARGET_COLS[name]).value = num_tys
|
||||
found = True
|
||||
break
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
break
|
||||
if found:
|
||||
break
|
||||
|
||||
processed += 1
|
||||
print(" %s → row %d: OK" % (code, target_row))
|
||||
|
||||
wb.save(TARGET_FILE)
|
||||
|
||||
print("\nResult: %d/%d processed, %d errors" % (processed, len(source_files), len(errors)))
|
||||
for e in errors:
|
||||
print(" ERROR:", e)
|
||||
|
||||
# Show result
|
||||
print("\nTarget values:")
|
||||
for code, row in sorted(code_to_row.items()):
|
||||
d = ws.cell(row, 4).value
|
||||
e = ws.cell(row, 5).value
|
||||
f_val = ws.cell(row, 6).value
|
||||
g = ws.cell(row, 7).value
|
||||
if d or e or f_val or g:
|
||||
print(" %s: СМР=%s Монт=%s Обор=%s Проч=%s" % (code, d, e, f_val, g))
|
||||
Reference in New Issue
Block a user