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>
This commit is contained in:
@@ -214,7 +214,7 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
|
|||||||
truncated = False
|
truncated = False
|
||||||
for r_idx, row in enumerate(ws.iter_rows(), 1):
|
for r_idx, row in enumerate(ws.iter_rows(), 1):
|
||||||
vals = [
|
vals = [
|
||||||
f"{c.column_letter}{r_idx}={str(c.value)[:150]}"
|
f"{c.column_letter}{r_idx}={str(c.value)[:300]}"
|
||||||
for c in row
|
for c in row
|
||||||
if c.value is not None and str(c.value).strip()
|
if c.value is not None and str(c.value).strip()
|
||||||
]
|
]
|
||||||
|
|||||||
+148
@@ -0,0 +1,148 @@
|
|||||||
|
"""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),
|
||||||
|
}
|
||||||
@@ -433,6 +433,72 @@ async def download_file(filename: str, request: Request):
|
|||||||
return FileResponse(fpath, filename=filename)
|
return FileResponse(fpath, filename=filename)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/extract_complaints")
|
||||||
|
async def extract_complaints_endpoint(request: Request):
|
||||||
|
"""Detrministic regex extraction of (пункт → смета) pairs from xlsm.
|
||||||
|
|
||||||
|
Body: {"tab_id": "...", "filename": "..."} — file must already be uploaded.
|
||||||
|
Returns: stats + pairs + no_code_rows.
|
||||||
|
"""
|
||||||
|
from complaints import extract_pairs
|
||||||
|
|
||||||
|
user = _get_user(request)
|
||||||
|
body = await request.json()
|
||||||
|
tab_id = body.get("tab_id") or request.headers.get("x-tab-id", "default")
|
||||||
|
filename = body.get("filename")
|
||||||
|
if not filename:
|
||||||
|
raise HTTPException(400, "filename required")
|
||||||
|
safe_name = Path(filename).name
|
||||||
|
fpath = get_work_dir(user, tab_id) / safe_name
|
||||||
|
if not fpath.exists():
|
||||||
|
raise HTTPException(404, "File not found in work directory")
|
||||||
|
try:
|
||||||
|
result = extract_pairs(fpath)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(400, str(e))
|
||||||
|
ip = request.client.host if request.client else None
|
||||||
|
log_action(user, "extract_complaints", "POST", "/api/extract_complaints",
|
||||||
|
f"{safe_name} pairs={result['stats']['total_pairs']}", ip, 200)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/apply_matches")
|
||||||
|
async def apply_matches_endpoint(request: Request):
|
||||||
|
"""Fill column D in sheet «РеестрСМ» with matching пункт-замечания.
|
||||||
|
|
||||||
|
Body: {"tab_id": "...", "filename": "..."} — original xlsm with both sheets.
|
||||||
|
Saves <stem>_filled.xlsm into the same work directory and returns
|
||||||
|
download URL + stats.
|
||||||
|
"""
|
||||||
|
from complaints import apply_to_registry
|
||||||
|
|
||||||
|
user = _get_user(request)
|
||||||
|
body = await request.json()
|
||||||
|
tab_id = body.get("tab_id") or request.headers.get("x-tab-id", "default")
|
||||||
|
filename = body.get("filename")
|
||||||
|
if not filename:
|
||||||
|
raise HTTPException(400, "filename required")
|
||||||
|
safe_name = Path(filename).name
|
||||||
|
work_dir = get_work_dir(user, tab_id)
|
||||||
|
fpath = work_dir / safe_name
|
||||||
|
if not fpath.exists():
|
||||||
|
raise HTTPException(404, "File not found in work directory")
|
||||||
|
out_name = f"{Path(safe_name).stem}_filled.xlsm"
|
||||||
|
out_path = work_dir / out_name
|
||||||
|
try:
|
||||||
|
result = apply_to_registry(fpath, out_path)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(400, str(e))
|
||||||
|
ip = request.client.host if request.client else None
|
||||||
|
log_action(user, "apply_matches", "POST", "/api/apply_matches",
|
||||||
|
f"{safe_name} filled={result['cells_filled']}", ip, 200)
|
||||||
|
return {
|
||||||
|
**result,
|
||||||
|
"output_filename": out_name,
|
||||||
|
"download_url": f"/api/files/{out_name}",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/reset")
|
@app.post("/api/reset")
|
||||||
async def reset_session(request: Request):
|
async def reset_session(request: Request):
|
||||||
user = _get_user(request)
|
user = _get_user(request)
|
||||||
|
|||||||
Reference in New Issue
Block a user