"""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) # Группируем строки реестра по коду сметы, разделяя видимые и скрытые. # В этом файле скрыто 2500 строк из 2978 (архив), и многие сметы из # замечаний есть ТОЛЬКО в скрытых. Поэтому стратегия: # 1) если у сметы есть видимая строка — пишем в первую видимую # 2) иначе — пишем в первую скрытую (увидится после unhide) visible_rows: dict[str, list[int]] = {} hidden_rows: dict[str, list[int]] = {} for r_idx in range(2, ws.max_row + 1): code = ws.cell(row=r_idx, column=REGISTRY_CODE_COL).value if not code: continue code = str(code).strip() rd = ws.row_dimensions.get(r_idx) bucket = hidden_rows if (rd is not None and rd.hidden) else visible_rows bucket.setdefault(code, []).append(r_idx) cells_filled = 0 filled_visible = 0 filled_hidden = 0 smety_matched: set[str] = set() for code, punkty in by_smeta_str.items(): if code in visible_rows: target_row = visible_rows[code][0] filled_visible += 1 elif code in hidden_rows: target_row = hidden_rows[code][0] filled_hidden += 1 else: continue ws.cell(row=target_row, column=REGISTRY_TARGET_COL, value=punkty) cells_filled += 1 smety_matched.add(code) wb.save(str(out_path)) return { "stats": extracted["stats"], "cells_filled": cells_filled, "filled_in_visible_rows": filled_visible, "filled_in_hidden_rows": filled_hidden, "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), }