Files
smeta-web/complaints.py
T
anorandClaude Opus 4.7 bfd3197efd feat: детерминированный матч пункт-замечания → ЛСР через regex+openpyxl
- complaints.py: extract_pairs() парсит лист 15.СМ regex-ом
  (?:ЛСР|ОСР|ЛС|ССР|ССРСС)-N(-N)+ — без LLM, видит весь текст
  замечаний независимо от его длины
- apply_to_registry() формирует обновлённый xlsm: для каждой уникальной
  сметы группирует пункты, пишет «80.1, 80.66, 80.108» в колонку D
  всех совпадающих строк РеестрСМ; сохраняет как <stem>_filled.xlsm
- main.py: POST /api/extract_complaints (preview), POST /api/apply_matches
  (запись + ссылка на скачивание через существующий /api/files/{name})
- claude_bridge_glm.py: cap значения ячейки 150 → 300 — длинные тексты
  замечаний теперь меньше режутся для обычного chat-режима

Многие-ко-многим: один пункт может относиться к нескольким сметам
(несколько строк pair), одной смете может относиться много пунктов
(пункты объединяются через «, » в одной ячейке D). Дубликаты строк
в РеестрСМ заполняются все.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 16:47:21 +10:00

149 lines
5.0 KiB
Python

"""Deterministic extraction of (пункт замечания → код сметы) pairs from xlsm.
Used by /api/extract_complaints and /api/apply_matches. Pure regex + openpyxl,
no LLM — for tasks where the input format is structural (smeta registry on
sheet "РеестрСМ" + complaints log on sheet "15.СМ"), determinism beats AI.
"""
from __future__ import annotations
import re
from pathlib import Path
import openpyxl
# Sheet names — fixed by user's xlsm convention
SHEET_COMPLAINTS = "15.СМ"
SHEET_REGISTRY_CANDIDATES = ("Реестр СМ", "РеестрСМ")
COMPLAINTS_TEXT_COL = 4 # column D
REGISTRY_CODE_COL = 3 # column C
REGISTRY_TARGET_COL = 4 # column D — пункт замечания ГГЭ
_PUNKT_RE = re.compile(r"^\s*(\d+[.,]\d+)\s*\(")
_CODE_RE = re.compile(r"(?:ЛСР|ОСР|ЛС|ССР|ССРСС)-\d+(?:-\d+)+")
def _open_registry_sheet(wb):
for name in SHEET_REGISTRY_CANDIDATES:
if name in wb.sheetnames:
return wb[name]
raise ValueError(
f"Не найден лист реестра. Ожидался один из: {SHEET_REGISTRY_CANDIDATES}"
)
def extract_pairs(path: str | Path) -> dict:
"""Read complaints sheet, return list of (пункт, смета) pairs + stats.
Returns:
{
"stats": {"total_complaints": N, "with_code": M, "without_code": K, "total_pairs": P},
"pairs": [{"row": 11, "пункт": "80.60", "смета": "ЛСР-..."}, ...],
"no_code_rows": [{"row": 23, "пункт": "80.5"}, ...], # для прозрачности
}
"""
wb = openpyxl.load_workbook(str(path), data_only=True)
if SHEET_COMPLAINTS not in wb.sheetnames:
raise ValueError(f"Не найден лист «{SHEET_COMPLAINTS}»")
ws = wb[SHEET_COMPLAINTS]
pairs = []
no_code = []
total = 0
with_code = 0
empty_streak = 0
for r_idx, row in enumerate(ws.iter_rows(values_only=True), 1):
# Header rows have no D-text complaint; first complaints typically start at R11
if r_idx < 11:
continue
d = row[COMPLAINTS_TEXT_COL - 1] if len(row) >= COMPLAINTS_TEXT_COL else None
if not d or not str(d).strip():
empty_streak += 1
if empty_streak >= 30:
break
continue
empty_streak = 0
text = str(d)
m = _PUNKT_RE.match(text)
if not m:
# Not a complaint line (could be a header/footer mid-table) — skip
continue
total += 1
punkt = m.group(1).replace(",", ".")
codes = _CODE_RE.findall(text)
# dedupe codes within one complaint, keep order
seen = set()
unique_codes = []
for c in codes:
if c not in seen:
seen.add(c)
unique_codes.append(c)
if not unique_codes:
no_code.append({"row": r_idx, "пункт": punkt})
continue
with_code += 1
for c in unique_codes:
pairs.append({"row": r_idx, "пункт": punkt, "смета": c})
return {
"stats": {
"total_complaints": total,
"with_code": with_code,
"without_code": len(no_code),
"total_pairs": len(pairs),
},
"pairs": pairs,
"no_code_rows": no_code,
}
def apply_to_registry(path: str | Path, out_path: str | Path) -> dict:
"""Extract pairs, then for each unique смета write `, `-joined sorted пункты
into column D of every РеестрСМ row whose column C matches.
Saves modified workbook to `out_path`. Returns counts (cells_filled, smety_with_punkty).
"""
extracted = extract_pairs(path)
pairs = extracted["pairs"]
# group by смета → set of пункты
by_smeta: dict[str, set[str]] = {}
for p in pairs:
by_smeta.setdefault(p["смета"], set()).add(p["пункт"])
# Sort пункты by numeric value: 80.5 < 80.60 < 80.115
def _punkt_key(s: str) -> tuple[float, str]:
try:
return (float(s), s)
except ValueError:
return (1e9, s)
by_smeta_str = {
s: ", ".join(sorted(punkty, key=_punkt_key))
for s, punkty in by_smeta.items()
}
wb = openpyxl.load_workbook(str(path))
ws = _open_registry_sheet(wb)
cells_filled = 0
smety_matched = set()
for r_idx in range(2, ws.max_row + 1):
code_cell = ws.cell(row=r_idx, column=REGISTRY_CODE_COL)
code = code_cell.value
if not code:
continue
code = str(code).strip()
if code in by_smeta_str:
ws.cell(row=r_idx, column=REGISTRY_TARGET_COL, value=by_smeta_str[code])
cells_filled += 1
smety_matched.add(code)
wb.save(str(out_path))
return {
"stats": extracted["stats"],
"cells_filled": cells_filled,
"smety_with_punkty": len(smety_matched),
"smety_total_in_pairs": len(by_smeta_str),
"smety_not_found_in_registry": sorted(set(by_smeta_str) - smety_matched),
}