Compare commits
10
Commits
53b4aa3ff5
...
4c282f9653
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c282f9653 | ||
|
|
15c864be22 | ||
|
|
1a7c179730 | ||
|
|
a9f3eabf27 | ||
|
|
811df5c103 | ||
|
|
ff207ab0fd | ||
|
|
3543314cdf | ||
|
|
e2635df90b | ||
|
|
bfd3197efd | ||
|
|
9f2e355298 |
@@ -215,7 +215,7 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
|
||||
truncated = False
|
||||
for r_idx, row in enumerate(ws.iter_rows(), 1):
|
||||
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
|
||||
if c.value is not None and str(c.value).strip()
|
||||
]
|
||||
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
"""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),
|
||||
}
|
||||
@@ -433,6 +433,74 @@ 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")
|
||||
# openpyxl drops VBA macros when saving — write as .xlsx so Excel
|
||||
# opens it cleanly even when the source was .xlsm
|
||||
out_name = f"{Path(safe_name).stem}_filled.xlsx"
|
||||
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)
|
||||
@@ -872,7 +940,10 @@ async def admin_download_file_endpoint(request: Request):
|
||||
@app.get("/admin", response_class=HTMLResponse)
|
||||
async def admin_page():
|
||||
# Auth check is done client-side (JS) + all /api/admin/* endpoints require admin
|
||||
return Path("static/admin.html").read_text(encoding="utf-8")
|
||||
html = Path("static/admin.html").read_text(encoding="utf-8")
|
||||
# Без no-cache браузер мог отдавать устаревший HTML, в котором loadUsers()
|
||||
# перезаписывал dropdown файлов и стирал результат loadFileUsers/loadFiles
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache, must-revalidate"})
|
||||
|
||||
|
||||
# === Batch V3: Generate + Verify + Auto-Retry ===
|
||||
|
||||
@@ -48,6 +48,7 @@ a { color: var(--accent); text-decoration: none; }
|
||||
<a href="#audit" onclick="showPage('audit')">Журнал</a>
|
||||
<a href="#files" onclick="showPage('files')">Файлы</a>
|
||||
<a href="/" class="back">← Вернуться в чат</a>
|
||||
<div style="position:absolute;bottom:.5rem;left:1rem;font-size:.65rem;color:#999">v.2026-05-06b</div>
|
||||
</nav>
|
||||
|
||||
<div class="main">
|
||||
|
||||
+11
-2
@@ -167,10 +167,19 @@ const API = '';
|
||||
let token = localStorage.getItem('token');
|
||||
let pendingFiles = [];
|
||||
let streaming = false;
|
||||
// crypto.randomUUID работает только в secure context (HTTPS / localhost),
|
||||
// под голым HTTP по IP его нет — используем fallback
|
||||
function genUUID() {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID();
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
|
||||
const r = Math.random() * 16 | 0;
|
||||
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
|
||||
});
|
||||
}
|
||||
// Session continuity: reuse last tabId from localStorage
|
||||
// New session only via "Новый чат" button or ?tab=UUID
|
||||
const urlTab = new URLSearchParams(window.location.search).get('tab');
|
||||
let tabId = urlTab || localStorage.getItem('tabId') || crypto.randomUUID();
|
||||
let tabId = urlTab || localStorage.getItem('tabId') || genUUID();
|
||||
localStorage.setItem('tabId', tabId);
|
||||
|
||||
function checkAdmin() {
|
||||
@@ -470,7 +479,7 @@ async function sendMessage() {
|
||||
// --- Session ---
|
||||
async function resetSession() {
|
||||
// Create new tab = new session, old one stays in DB
|
||||
tabId = crypto.randomUUID();
|
||||
tabId = genUUID();
|
||||
localStorage.setItem('tabId', tabId);
|
||||
msgs.innerHTML = '';
|
||||
addMsg('system', 'Новый диалог начат.');
|
||||
|
||||
Reference in New Issue
Block a user