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:
anor
2026-05-06 16:47:21 +10:00
co-authored by Claude Opus 4.7
parent 9f2e355298
commit bfd3197efd
3 changed files with 215 additions and 1 deletions
+66
View File
@@ -433,6 +433,72 @@ async def download_file(filename: str, request: Request):
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")
async def reset_session(request: Request):
user = _get_user(request)