285 lines
13 KiB
Python
285 lines
13 KiB
Python
"""Conservative, source-linked comparison of uploaded estimate workbooks."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from decimal import Decimal, InvalidOperation
|
||
from difflib import SequenceMatcher
|
||
from hashlib import sha256
|
||
from pathlib import Path
|
||
import re
|
||
|
||
MAX_ROWS = 5000
|
||
MAX_COLUMNS = 80
|
||
MAX_FILE_BYTES = 30 * 1024 * 1024
|
||
|
||
|
||
def _norm(value: object) -> str:
|
||
return re.sub(r"\s+", " ", str(value or "").casefold().replace("ё", "е")).strip()
|
||
|
||
|
||
def _field(header: object) -> str | None:
|
||
h = _norm(header)
|
||
if not h:
|
||
return None
|
||
if "наименован" in h or h in {"ресурс", "работа", "вид работ"}:
|
||
return "name"
|
||
if "ед. изм" in h or "единица измерения" in h or h == "единица":
|
||
return "unit"
|
||
if "код" in h or "шифр" in h:
|
||
return "code"
|
||
if "количеств" in h or "объем" in h or "объём" in h:
|
||
return "quantity"
|
||
if "отпускная" in h and "ндс" in h and "без" not in h:
|
||
return "price_with_vat"
|
||
if "цена" in h and "ндс" in h and "без" not in h:
|
||
return "price_with_vat"
|
||
if "сметная цена" in h and "без" in h and "ндс" in h:
|
||
return "price_no_vat"
|
||
if ("стоимость" in h or "цена" in h) and ("на единицу" in h or "единицу измерения" in h):
|
||
return "unit_price"
|
||
return None
|
||
|
||
|
||
def _number(value: object) -> str | None:
|
||
if value is None or isinstance(value, bool):
|
||
return None
|
||
s = str(value).strip().replace("\u00a0", "").replace(" ", "")
|
||
if not s:
|
||
return None
|
||
if "," in s and "." in s:
|
||
return None # ambiguous decimal notation
|
||
try:
|
||
amount = Decimal(s.replace(",", "."))
|
||
except InvalidOperation:
|
||
return None
|
||
if not amount.is_finite():
|
||
return None
|
||
if abs(amount) > Decimal("1000000000000"):
|
||
return None
|
||
try:
|
||
return str(amount.quantize(Decimal("0.01")))
|
||
except InvalidOperation:
|
||
return None
|
||
|
||
|
||
def _safe_file(work_dir: Path, filename: str) -> Path:
|
||
if not filename or filename in {".", ".."} or Path(filename).name != filename or "\\" in filename:
|
||
raise ValueError("Недопустимое имя файла")
|
||
root = Path(work_dir).resolve()
|
||
path = root / filename
|
||
if path.is_symlink() or path.resolve().parent != root:
|
||
raise ValueError("Файл вне рабочей папки")
|
||
if path.suffix.lower() not in {".xlsx", ".xlsm"}:
|
||
raise ValueError("Поддерживаются только xlsx/xlsm")
|
||
if not path.is_file() or path.stat().st_size > MAX_FILE_BYTES:
|
||
raise ValueError("Файл не найден или превышает 30 МБ")
|
||
return path
|
||
|
||
|
||
def file_fingerprint(work_dir: Path, filename: str) -> str:
|
||
path = _safe_file(work_dir, filename)
|
||
digest = sha256()
|
||
with path.open("rb") as stream:
|
||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||
digest.update(chunk)
|
||
return digest.hexdigest()
|
||
|
||
|
||
def list_workbooks(work_dir: Path) -> list[dict]:
|
||
"""List eligible uploaded files and sheets without reading document rows."""
|
||
import openpyxl
|
||
from xlsx_utils import assert_xlsx_not_bomb
|
||
|
||
root = Path(work_dir)
|
||
if not root.is_dir():
|
||
return []
|
||
found = []
|
||
for path in sorted(root.iterdir(), key=lambda p: p.name.casefold()):
|
||
if path.suffix.lower() not in {".xlsx", ".xlsm"} or path.name.startswith("~$"):
|
||
continue
|
||
try:
|
||
safe = _safe_file(root, path.name)
|
||
assert_xlsx_not_bomb(safe)
|
||
book = openpyxl.load_workbook(safe, read_only=True, data_only=True)
|
||
try:
|
||
found.append({"filename": path.name, "sheets": list(book.sheetnames)})
|
||
finally:
|
||
book.close()
|
||
except Exception:
|
||
# A corrupt workbook is never offered as a source.
|
||
continue
|
||
return found
|
||
|
||
|
||
def read_table(work_dir: Path, filename: str, sheet: str, role: str) -> dict:
|
||
import openpyxl
|
||
from xlsx_utils import assert_xlsx_not_bomb
|
||
|
||
if role not in {"ka", "lsr", "vor", "kp"}:
|
||
raise ValueError("Неизвестный тип документа")
|
||
path = _safe_file(work_dir, filename)
|
||
assert_xlsx_not_bomb(path)
|
||
fingerprint = file_fingerprint(work_dir, filename)
|
||
book = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||
try:
|
||
if sheet not in book.sheetnames:
|
||
raise ValueError("Лист не найден")
|
||
ws = book[sheet]
|
||
header_row = None
|
||
columns = {}
|
||
for row_idx, cells in enumerate(ws.iter_rows(min_row=1, max_row=30, max_col=MAX_COLUMNS,
|
||
values_only=True), 1):
|
||
mapping = {}
|
||
duplicates = set()
|
||
for col_idx, cell in enumerate(cells):
|
||
field = _field(cell)
|
||
if field in mapping:
|
||
duplicates.add(field)
|
||
elif field:
|
||
mapping[field] = col_idx
|
||
needed = {"name", "unit"}
|
||
metric = ({"price_no_vat", "price_with_vat"} if role == "ka" else
|
||
{"unit_price", "quantity"} if role == "lsr" else
|
||
{"quantity"} if role == "vor" else
|
||
{"price_with_vat", "unit_price"})
|
||
if needed <= mapping.keys() and metric & mapping.keys():
|
||
if duplicates:
|
||
raise ValueError("Неоднозначные заголовки: " + ", ".join(sorted(duplicates)))
|
||
header_row, columns = row_idx, mapping
|
||
break
|
||
if header_row is None:
|
||
raise ValueError("Не найдены однозначные заголовки имени, единицы и цены/объёма")
|
||
rows = []
|
||
for row_idx, cells in enumerate(ws.iter_rows(min_row=header_row + 1,
|
||
max_row=header_row + MAX_ROWS + 1,
|
||
max_col=MAX_COLUMNS, values_only=True), header_row + 1):
|
||
if len(rows) >= MAX_ROWS:
|
||
break
|
||
name = str(cells[columns["name"]] or "").strip()
|
||
if not name:
|
||
continue
|
||
values = {}
|
||
for field in ("price_no_vat", "price_with_vat", "unit_price", "quantity"):
|
||
if field in columns:
|
||
parsed = _number(cells[columns[field]])
|
||
if parsed is not None:
|
||
values[field] = parsed
|
||
rows.append({"file": filename, "sheet": sheet, "row": row_idx,
|
||
"code": str(cells[columns["code"]] or "").strip() if "code" in columns else "",
|
||
"name": name,
|
||
"unit": str(cells[columns["unit"]] or "").strip(),
|
||
"values": values})
|
||
return {"file": filename, "sheet": sheet, "role": role,
|
||
"fields": list(columns),
|
||
"fingerprint": fingerprint, "rows": rows,
|
||
"truncated": (ws.max_row or 0) > header_row + MAX_ROWS}
|
||
finally:
|
||
book.close()
|
||
|
||
|
||
def _unit(value: str) -> str:
|
||
u = _norm(value).replace(".", "").replace("²", "2").replace("³", "3")
|
||
return {"штука": "шт", "штук": "шт", "м кв": "м2", "кв м": "м2",
|
||
"м куб": "м3", "куб м": "м3"}.get(u, u)
|
||
|
||
|
||
def _candidate(left: dict, right: dict) -> tuple[float, bool, str]:
|
||
same_code = bool(left["code"] and right["code"] and _norm(left["code"]) == _norm(right["code"]))
|
||
same_name = _norm(left["name"]) == _norm(right["name"])
|
||
unit_ok = bool(_unit(left["unit"]) and _unit(left["unit"]) == _unit(right["unit"]))
|
||
ratio = SequenceMatcher(None, _norm(left["name"]), _norm(right["name"])).ratio()
|
||
score = (2 if same_code else 0) + (1 if same_name else ratio) + (0.25 if unit_ok else 0)
|
||
auto = unit_ok and (same_code or (not left["code"] and same_name))
|
||
return score, auto, ("Точный код" if same_code else "Точное название" if same_name else "Похожее название")
|
||
|
||
|
||
def detect_mode(question: str) -> str | None:
|
||
q = _norm(question)
|
||
if not any(term in q for term in ("сравн", "свер", "сопостав")):
|
||
return None
|
||
ka = bool(re.search(r"\bка\b", q) or "конъюнктур" in q)
|
||
lsr = bool(re.search(r"\bлср\b", q) or "локальн" in q or "смет" in q)
|
||
vor = bool(re.search(r"\bвор\b", q) or "ведомост" in q)
|
||
kp = bool(re.search(r"\bкп\b", q) or "коммерческ" in q)
|
||
if ka and lsr:
|
||
return "ka_lsr"
|
||
if vor and lsr:
|
||
return "vor_lsr"
|
||
if ka and kp:
|
||
return "ka_kp"
|
||
return None
|
||
|
||
|
||
def compare(left: dict, right: dict, mode: str, *, choices: dict | None = None,
|
||
price_fields: dict | None = None) -> dict:
|
||
roles = {"ka_lsr": ("ka", "lsr"), "vor_lsr": ("vor", "lsr"), "ka_kp": ("ka", "kp")}
|
||
if mode not in roles or (left["role"], right["role"]) != roles[mode]:
|
||
raise ValueError("Несовместимые типы документов")
|
||
choices, price_fields = choices or {}, price_fields or {}
|
||
result = []
|
||
by_code: dict[str, set[int]] = {}
|
||
by_name: dict[str, set[int]] = {}
|
||
by_token: dict[str, set[int]] = {}
|
||
for other_index, other in enumerate(right["rows"]):
|
||
if other["code"]:
|
||
by_code.setdefault(_norm(other["code"]), set()).add(other_index)
|
||
by_name.setdefault(_norm(other["name"]), set()).add(other_index)
|
||
for token in set(re.findall(r"[\w-]{4,}", _norm(other["name"]))):
|
||
by_token.setdefault(token, set()).add(other_index)
|
||
for index, row in enumerate(left["rows"]):
|
||
ranked = []
|
||
exact = set(by_code.get(_norm(row["code"]), ())) if row["code"] else set()
|
||
exact.update(by_name.get(_norm(row["name"]), ()))
|
||
relevant = set(exact)
|
||
for token in set(re.findall(r"[\w-]{4,}", _norm(row["name"]))):
|
||
relevant.update(by_token.get(token, ()))
|
||
candidate_indices = sorted(exact)[:100] + sorted(relevant - exact)[:100]
|
||
for other_index in candidate_indices:
|
||
other = right["rows"][other_index]
|
||
score, auto, reason = _candidate(row, other)
|
||
if score >= 0.45:
|
||
ranked.append((score, other_index, auto, reason))
|
||
ranked.sort(key=lambda hit: (-hit[0], hit[1]))
|
||
candidates = [{"index": idx, "reason": reason, "code": right["rows"][idx]["code"],
|
||
"name": right["rows"][idx]["name"], "unit": right["rows"][idx]["unit"],
|
||
"file": right["file"], "sheet": right["sheet"], "row": right["rows"][idx]["row"]}
|
||
for _, idx, _, reason in ranked[:5]]
|
||
selected = choices.get(index)
|
||
if selected == -1:
|
||
selected = None
|
||
elif selected is not None:
|
||
if not isinstance(selected, int) or selected < 0 or selected >= len(right["rows"]):
|
||
raise ValueError("Выбранной строки нет в исходном файле")
|
||
elif ranked and ranked[0][2] and (len(ranked) == 1 or ranked[0][0] > ranked[1][0]):
|
||
selected = ranked[0][1]
|
||
left_field = price_fields.get(index, "price_no_vat" if mode == "ka_lsr" else
|
||
"quantity" if mode == "vor_lsr" else "price_with_vat")
|
||
allowed = {"ka_lsr": {"price_no_vat", "price_with_vat"},
|
||
"vor_lsr": {"quantity"}, "ka_kp": {"price_with_vat", "price_no_vat"}}[mode]
|
||
if left_field not in allowed or left_field not in left.get("fields", row["values"]):
|
||
raise ValueError("Выбранного столбца нет в исходном файле")
|
||
right_field = "quantity" if mode == "vor_lsr" else "unit_price" if mode == "ka_lsr" else "price_with_vat"
|
||
warning = ""
|
||
difference = None
|
||
right_row = right["rows"][selected] if selected is not None else None
|
||
if right_row is None:
|
||
warning = "Совпадение не подтверждено"
|
||
elif _unit(row["unit"]) != _unit(right_row["unit"]) or not _unit(row["unit"]):
|
||
warning = "Несовместимые единицы измерения"
|
||
elif mode == "ka_lsr" and left_field == "price_with_vat":
|
||
warning = "Цена с НДС и сметная стоимость: база НДС не совпадает"
|
||
elif left_field not in row["values"] or right_field not in right_row["values"]:
|
||
warning = "В исходной строке нет числового значения"
|
||
else:
|
||
difference = str((Decimal(right_row["values"][right_field]) -
|
||
Decimal(row["values"][left_field])).quantize(Decimal("0.01")))
|
||
result.append({"index": index, "left": row, "match_index": selected,
|
||
"right": right_row, "left_field": left_field, "right_field": right_field,
|
||
"difference": difference, "warning": warning, "candidates": candidates})
|
||
matched = {r["match_index"] for r in result if r["match_index"] is not None}
|
||
unmatched_right = len(right["rows"]) - len(matched) if mode == "vor_lsr" else 0
|
||
return {"mode": mode, "left": left, "right": right, "rows": result,
|
||
"unmatched_right": unmatched_right,
|
||
"complete": bool(result) and not left["truncated"] and not right["truncated"] and
|
||
unmatched_right == 0 and all(r["difference"] is not None for r in result)}
|