feat: корпус реальных смет/КА/ВОР — поиск расценок, цен и объёмов из сданного проекта
Три обезличенных индекса из базы реального проекта (gge_deep — глубокий разбор всех схем): расценки с полным ресурсным составом + ценой/накладными/обоснованиями, КА-цены (winner + офферы поставщиков «Поставщик N»), ВОР-объёмы с формулами расчёта. Поиск (find_in_real_estimates / find_ka_price / find_in_vor) заведён в smeta_mcp и tools_glm (активный прод-бэкенд glm). Обезличивание verify_corpus: exit 0. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
# Корпус реальных смет, КА и ВОР (обезличенный)
|
||||
|
||||
Поисковая база из сданного комплекта смет реального проекта
|
||||
(`_РИМ…передача`, 3.1 ГБ на внешнем SSD). Даёт ассистенту grounding в
|
||||
**реальных экспертных решениях**, дополняя нормативный поиск ФСНБ/ФССЦ.
|
||||
|
||||
## Три индекса (`data/real_corpus/`, обезличены)
|
||||
|
||||
| Файл | Что | Источник |
|
||||
|------|-----|----------|
|
||||
| `estimates_index.json` (~10 МБ) | 3097 расценок с ПОЛНЫМ составом: работа→код ГЭСН→ед→**ресурсы (рабочие/машины/материалы с нормами и ценами)**→цена/ед→трудозатраты→накладные/прибыль (с обоснованием)→коэффициенты→freq→объём. + 6796 прямых материалов с ценами | 2519 `.gge` ЛСР/ОСР (67 256 позиций) |
|
||||
| `ka_index.json` (~3.7 МБ) | 3922 материала: цена min/median/max/**winner**→обезличенные офферы→регион→квартал | 181 zip КА (4587 позиций) |
|
||||
| `vor_index.json` (~8 МБ) | 25 834 работы: ед→объём (min/median/max)→**формула расчёта**→ссылка на лист обоснования | 1951 `.gge` ВОР, схема QuantityTakeoff |
|
||||
|
||||
## Поиск (3 MCP-tool + glm-tool)
|
||||
|
||||
`real_corpus.py`:
|
||||
- `find_in_real_estimates(query)` — расценка с составом под работу
|
||||
- `find_ka_price(query)` — цена материала (КА-рынок + прямые материалы смет)
|
||||
- `find_in_vor(query)` — как считали объём работы
|
||||
|
||||
Заведены в `smeta_mcp.py` (MCP) И `tools_glm.py` (активный прод-бэкенд
|
||||
`AI_BACKEND=glm`, исполнение in-process). Морфология: pymorphy2 если есть,
|
||||
иначе префиксный fallback (stdlib) — самосогласовано, пересборка не нужна.
|
||||
|
||||
## Парсинг
|
||||
|
||||
`gge_deep.py` — глубокий разбор всех схем:
|
||||
- ЛСР/ОСР (`LocalEstimate`/`ObjectEstimate`) → состав, цены база/текущие, накладные, коэффициенты
|
||||
- ВОР (`QuantityTakeoff`) → работа→объём→формула→источник
|
||||
- КА (`MarketAnalysis`) парсится в `scripts/build_ka_index.py`
|
||||
|
||||
## Пересборка / проверка
|
||||
|
||||
```bash
|
||||
python3 scripts/build_real_corpus.py "<путь к базе>" # сметы
|
||||
python3 scripts/build_ka_index.py "<путь к базе>" # КА
|
||||
python3 scripts/build_vor_index.py "<путь к базе>" # ВОР
|
||||
python3 scripts/verify_corpus.py # exit 0 = обезличено + поиск находит
|
||||
```
|
||||
|
||||
## Обезличивание (единый `gge_deep.scrub`)
|
||||
|
||||
Чистит: имя проекта, код договора `960-06…`, пикеты `ПК5555+`, аббревиатуру
|
||||
`ВСМ`, станцию «Новая Тверь», ФИО, GUID; КА-поставщики → «Поставщик N»
|
||||
(ИНН/КПП/сайт/название фирмы убраны). Сохраняет: технику, обоснования
|
||||
(Приказы Минстроя), регионы (вкл. города поставщиков), бренды товаров (ПК-3).
|
||||
Проверка `verify_corpus.py`: проект-токены и реквизиты = 0.
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+224
@@ -0,0 +1,224 @@
|
||||
"""gge_deep — глубокий разбор .gge: вытаскивает ВСЁ ценное, что
|
||||
parse_gge_file пропускает (ресурсный состав, цены база/текущие, индексы,
|
||||
накладные/прибыль с обоснованиями, коэффициенты, трудозатраты), плюс разбор
|
||||
ВОР (QuantityTakeoff — работа→объём→формула→ссылка на обоснование).
|
||||
|
||||
Используется индексаторами корпуса (scripts/build_*). Обезличивание —
|
||||
ответственность вызывающего (scrub применяется в индексаторе), но имена
|
||||
подписантов/ФИО и идентификаторы объекта здесь НЕ извлекаются вовсе.
|
||||
|
||||
Зависимости: только stdlib (xml.etree). Совместимо с sandbox.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
# Проект-специфичные идентификаторы для обезличивания (scrub в индексаторах).
|
||||
DENY_RE = re.compile(
|
||||
r"создани\w*\s+высокоскоростн\w*|высокоскоростн\w*|санкт-петербург\s*[–-]\s*москва"
|
||||
r"|крюков\w*|алабушев\w*|вохр|960-06[\w.\-]*|ПК\s?\d+(?:\+\d+(?:,\d+)?)?"
|
||||
r"|\bВСМ[\w.\-]*|нов\w*\s+тверь",
|
||||
re.IGNORECASE)
|
||||
|
||||
|
||||
def scrub(text: str) -> str:
|
||||
return DENY_RE.sub("[…]", text) if text else text
|
||||
|
||||
|
||||
def _t(el, path: str) -> str:
|
||||
if el is None:
|
||||
return ""
|
||||
node = el.find(path)
|
||||
return (node.text or "").strip() if node is not None and node.text else ""
|
||||
|
||||
|
||||
def _f(s: str) -> float:
|
||||
try:
|
||||
return float(s)
|
||||
except (ValueError, TypeError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _resources(cost) -> dict:
|
||||
"""Ресурсный состав расценки (нормы на единицу): рабочие/машины/материалы."""
|
||||
out = {"workers": [], "machines": [], "materials": []}
|
||||
ri = cost.find("ResourcesInternal")
|
||||
if ri is None:
|
||||
return out
|
||||
for w in ri.findall("Worker"):
|
||||
out["workers"].append({
|
||||
"name": (_t(w, "Name") or "").strip(),
|
||||
"consumption": _f(_t(w, "Consumption")),
|
||||
"unit": _t(w, "Unit"),
|
||||
"price_cur": _f(_t(w, "PricePerUnitCur")),
|
||||
})
|
||||
for m in ri.findall("Machine"):
|
||||
out["machines"].append({
|
||||
"code": _t(m, "Code"),
|
||||
"name": _t(m, "Name"),
|
||||
"consumption": _f(_t(m, "Consumption")),
|
||||
"unit": _t(m, "Unit"),
|
||||
"price_base": _f(_t(m, "PricePerUnitBase")),
|
||||
"price_cur": _f(_t(m, "PricePerUnitCur")),
|
||||
"machinist_grade": _t(m, "Machinist/Grade"),
|
||||
})
|
||||
for mat in ri.findall("Material"):
|
||||
out["materials"].append({
|
||||
"code": _t(mat, "Code"),
|
||||
"name": _t(mat, "Name"),
|
||||
"consumption": _f(_t(mat, "Consumption")),
|
||||
"unit": _t(mat, "Unit"),
|
||||
"price_base": _f(_t(mat, "PricePerUnitBase")),
|
||||
"price_cur": _f(_t(mat, "PricePerUnitCur")),
|
||||
})
|
||||
# Внешние ресурсы (оборудование/неучтённые материалы из Cost/Resources)
|
||||
ext = cost.find("Resources")
|
||||
if ext is not None:
|
||||
for mat in ext.findall("Material"):
|
||||
out["materials"].append({
|
||||
"code": _t(mat, "Code"),
|
||||
"name": _t(mat, "Name"),
|
||||
"consumption": _f(_t(mat, "Consumption")),
|
||||
"unit": _t(mat, "Unit"),
|
||||
"price_base": _f(_t(mat, "PricePerUnitBase")),
|
||||
"price_cur": _f(_t(mat, "PricePerUnitCur")),
|
||||
"external": True,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _coefficients(cost) -> list[dict]:
|
||||
out = []
|
||||
cs = cost.find("Coefficients")
|
||||
if cs is None:
|
||||
return out
|
||||
for c in cs.findall("Coefficient"):
|
||||
val = c.find(".//Values/Value/CoefValue")
|
||||
out.append({
|
||||
"name": _t(c, "Name"),
|
||||
"reason": _t(c, "Reason"),
|
||||
"value": (val.text or "").strip() if val is not None and val.text else "",
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def parse_estimate_full(path: Path) -> dict:
|
||||
"""Полный разбор ЛСР/ОСР. Возвращает estimate-метаданные + позиции с
|
||||
ресурсным составом, ценами база/текущие, накладными/прибылью, коэффициентами."""
|
||||
try:
|
||||
root = ET.parse(str(path)).getroot()
|
||||
except (ET.ParseError, OSError) as e:
|
||||
return {"error": f"{type(e).__name__}: {e}", "path": str(path)}
|
||||
|
||||
schema = root.attrib.get(
|
||||
"{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation", "")
|
||||
est = root.find(".//Object/Estimate")
|
||||
if est is None:
|
||||
est = root.find(".//Estimate")
|
||||
|
||||
region = _t(est, "Region/RegionName")
|
||||
plb = est.find("PriceLevelBase") if est is not None else None
|
||||
plc = est.find("PriceLevelCur") if est is not None else None
|
||||
price_base = f"{_t(plb,'Year')} Q{_t(plb,'Quarter')}" if plb is not None else ""
|
||||
price_cur = f"{_t(plc,'Year')} Q{_t(plc,'Quarter')}" if plc is not None else ""
|
||||
|
||||
positions = []
|
||||
direct_materials = []
|
||||
for it in root.iter("Item"):
|
||||
cost = it.find("Cost")
|
||||
if cost is None:
|
||||
# Прямой материал в смете (Item/Material — напр. песок с реальной ценой)
|
||||
dm = it.find("Material")
|
||||
if dm is not None and _t(dm, "Name"):
|
||||
direct_materials.append({
|
||||
"code": _t(dm, "Code"),
|
||||
"name": (_t(dm, "Name") or "").strip(),
|
||||
"unit": _t(dm, "Unit"),
|
||||
"consumption": _f(_t(dm, "ConsumptionTotal")) or _f(_t(dm, "Consumption")),
|
||||
"price_cur": _f(_t(dm, "PricePerUnitCur")),
|
||||
})
|
||||
# Перевозочная позиция (Transport — доставка грузов)
|
||||
tr = it.find("Transport")
|
||||
if tr is not None and _t(tr, "Name"):
|
||||
qty = _f(_t(tr, "QuantityTotal")) or _f(_t(tr, "Quantity"))
|
||||
direct = _f(_t(tr, "Totals/Current/Direct")) or _f(_t(tr, "PriceTotalCur"))
|
||||
positions.append({
|
||||
"code": _t(tr, "Code"), "name": (_t(tr, "Name") or "").strip(),
|
||||
"prefix": _t(tr, "Prefix"), "unit": _t(tr, "Unit"),
|
||||
"quantity": qty,
|
||||
"labor_ch": 0.0, "machinist_ch": 0.0,
|
||||
"unit_cost_cur": round(direct / qty, 2) if qty else 0.0,
|
||||
"overhead": None, "profit": None, "coefficients": [],
|
||||
"resources": {"workers": [], "machines": [], "materials": []},
|
||||
"kind": "transport",
|
||||
})
|
||||
continue
|
||||
name = (_t(cost, "Name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
qty_total = _f(_t(cost, "QuantityTotal")) or _f(_t(cost, "Quantity"))
|
||||
direct_cur = _f(_t(cost, "Totals/Current/Direct"))
|
||||
unit_cost_cur = round(direct_cur / qty_total, 2) if qty_total else 0.0
|
||||
ov = it.find("Overheads")
|
||||
pr = it.find("Profits")
|
||||
positions.append({
|
||||
"code": _t(cost, "Code"),
|
||||
"name": name,
|
||||
"prefix": _t(cost, "Prefix"),
|
||||
"unit": _t(cost, "Unit"),
|
||||
"quantity": qty_total,
|
||||
"labor_ch": _f(_t(cost, "PerUnit/LaborCosts")),
|
||||
"machinist_ch": _f(_t(cost, "PerUnit/MachinistLaborCosts")),
|
||||
"unit_cost_cur": unit_cost_cur,
|
||||
"overhead": {"value": _t(ov, "Value"), "target": _t(ov, "Target"),
|
||||
"reason": _t(ov, "Reason")} if ov is not None else None,
|
||||
"profit": {"value": _t(pr, "Value"), "target": _t(pr, "Target"),
|
||||
"reason": _t(pr, "Reason")} if pr is not None else None,
|
||||
"coefficients": _coefficients(cost),
|
||||
"resources": _resources(cost),
|
||||
"kind": "cost",
|
||||
})
|
||||
|
||||
return {
|
||||
"schema": schema,
|
||||
"code": _t(est, "Num"),
|
||||
"region": region,
|
||||
"price_base": price_base,
|
||||
"price_cur": price_cur,
|
||||
"positions": positions,
|
||||
"direct_materials": direct_materials,
|
||||
}
|
||||
|
||||
|
||||
def parse_vor(path: Path) -> dict:
|
||||
"""Разбор ВОР (QuantityTakeoff): секции → работы (объём, формула, ссылка)."""
|
||||
try:
|
||||
root = ET.parse(str(path)).getroot()
|
||||
except (ET.ParseError, OSError) as e:
|
||||
return {"error": f"{type(e).__name__}: {e}", "path": str(path)}
|
||||
|
||||
works = []
|
||||
for sec in root.iter("Section"):
|
||||
sec_name = _t(sec, "Name")
|
||||
for w in sec.iter("Work"):
|
||||
name = (_t(w, "Name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
link = w.find(".//Link")
|
||||
source = _t(link, "PageDescription") if link is not None else ""
|
||||
works.append({
|
||||
"section": sec_name,
|
||||
"name": name,
|
||||
"unit": _t(w, "Unit"),
|
||||
"quantity": _f(_t(w, "Quantity")),
|
||||
"formula": _t(w, "QuantityFormula"),
|
||||
"comment": _t(w, "Comment"),
|
||||
"source": source,
|
||||
})
|
||||
return {
|
||||
"num": _t(root, "Num"),
|
||||
"reason": _t(root, "Reason"),
|
||||
"works": works,
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
"""real_corpus — поиск по обезличенному корпусу реальных смет (и КА).
|
||||
|
||||
Даёт ассистенту grounding в РЕАЛЬНЫХ применённых расценках сданного проекта,
|
||||
дополняя нормативный поиск (search_engine.py по ФСНБ/ФССЦ). Где нормативный
|
||||
поиск отвечает «какие расценки существуют», этот — «какие расценки реально
|
||||
применяли эксперты под эту работу и как часто».
|
||||
|
||||
Индексы строятся scripts/build_real_corpus.py и build_ka_index.py,
|
||||
обезличены, лежат в data/real_corpus/. Стиль поиска зеркалит search_engine.py
|
||||
(pymorphy2-нормализация + overlap-скоринг), без внешних сервисов.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
_DATA = Path(__file__).resolve().parent / "data" / "real_corpus"
|
||||
|
||||
_est_cache: dict | None = None
|
||||
_ka_cache: dict | None = None
|
||||
_vor_cache: dict | None = None
|
||||
|
||||
# Морфология опциональна: в проде есть pymorphy2 (как в search_engine.py),
|
||||
# в sandbox/локально — лёгкий стеммер на stdlib. Нормализация применяется
|
||||
# одинаково к индексу и запросу в одном процессе, поэтому самосогласована
|
||||
# при любом из двух движков (пересборка индекса не нужна).
|
||||
try:
|
||||
import pymorphy2
|
||||
_morph = pymorphy2.MorphAnalyzer()
|
||||
except ImportError: # pragma: no cover
|
||||
_morph = None
|
||||
|
||||
_PREFIX_LEN = 5 # длина префикса для fallback-нормализации без pymorphy2
|
||||
|
||||
|
||||
def _normalize(word: str) -> str:
|
||||
word = re.sub(r"[^\w]", "", word).lower()
|
||||
if len(word) <= 2 or word.isdigit():
|
||||
return word
|
||||
if _morph is not None:
|
||||
return _morph.parse(word)[0].normal_form
|
||||
# Fallback: усечение до префикса сводит словоформы к общему корню
|
||||
# («армир»овать=«армир»ование, «засып»ать=«засып»ка) консистентно
|
||||
# и без словаря. Грубее лемматизации, но устойчиво для overlap-скоринга.
|
||||
return word[:_PREFIX_LEN]
|
||||
|
||||
|
||||
def _terms(text: str) -> set[str]:
|
||||
return {_normalize(t) for t in re.split(r"\W+", text) if len(t) > 2}
|
||||
|
||||
|
||||
def _load_estimates() -> dict:
|
||||
global _est_cache
|
||||
if _est_cache is None:
|
||||
p = _DATA / "estimates_index.json"
|
||||
_est_cache = json.loads(p.read_text(encoding="utf-8")) if p.exists() else {"items": []}
|
||||
items = _est_cache["items"]
|
||||
df: dict[str, int] = {}
|
||||
for it in items:
|
||||
it["_terms"] = _terms(it["name"])
|
||||
for t in it["_terms"]:
|
||||
df[t] = df.get(t, 0) + 1
|
||||
# IDF: редкие отличительные слова («гидроизоляция») весят больше
|
||||
# частых generic («устройство», «грунт»), чтобы специфичная расценка
|
||||
# не тонула под более частой с теми же общими словами.
|
||||
n = max(1, len(items))
|
||||
_est_cache["_idf"] = {t: math.log(1 + n / c) for t, c in df.items()}
|
||||
for m in _est_cache.get("materials", []):
|
||||
m["_terms"] = _terms(m["name"])
|
||||
return _est_cache
|
||||
|
||||
|
||||
def _load_vor() -> dict:
|
||||
global _vor_cache
|
||||
if _vor_cache is None:
|
||||
p = _DATA / "vor_index.json"
|
||||
_vor_cache = json.loads(p.read_text(encoding="utf-8")) if p.exists() else {"items": []}
|
||||
for it in _vor_cache["items"]:
|
||||
it["_terms"] = _terms(it["name"])
|
||||
return _vor_cache
|
||||
|
||||
|
||||
def _load_ka() -> dict:
|
||||
global _ka_cache
|
||||
if _ka_cache is None:
|
||||
p = _DATA / "ka_index.json"
|
||||
_ka_cache = json.loads(p.read_text(encoding="utf-8")) if p.exists() else {"items": []}
|
||||
for it in _ka_cache["items"]:
|
||||
it["_terms"] = _terms(it["name"])
|
||||
return _ka_cache
|
||||
|
||||
|
||||
def find_in_real_estimates(query: str, top_k: int = 5) -> list[dict]:
|
||||
"""Найти реальные применённые расценки под описание работы.
|
||||
|
||||
Возвращает расценку с полным составом: code, name, unit, prefix, kind, freq,
|
||||
norm_sets, regions, qty, цена/ед, трудозатраты, накладные/прибыль (с
|
||||
обоснованием), коэффициенты, ресурсы (рабочие/машины/материалы), examples.
|
||||
"""
|
||||
data = _load_estimates()
|
||||
q = query.strip()
|
||||
qset = _terms(q)
|
||||
if not qset and not q:
|
||||
return []
|
||||
idf = data["_idf"]
|
||||
results = []
|
||||
for it in data["items"]:
|
||||
common = qset & it["_terms"]
|
||||
if not common and it["code"] not in q:
|
||||
continue
|
||||
score = sum(idf.get(t, 0.0) for t in common)
|
||||
if it["code"] and it["code"] in q:
|
||||
score += 100.0
|
||||
if score > 0:
|
||||
results.append((score, it["freq"], it))
|
||||
results.sort(key=lambda x: (x[0], x[1]), reverse=True)
|
||||
keys = ("code", "name", "unit", "prefix", "kind", "freq", "norm_sets", "regions",
|
||||
"qty", "unit_cost_cur", "labor_ch", "machinist_ch", "price_base",
|
||||
"price_cur", "overhead", "profit", "coefficients", "resources", "examples")
|
||||
return [{k: it.get(k) for k in keys} for _, _, it in results[:top_k]]
|
||||
|
||||
|
||||
def find_ka_price(query: str, top_k: int = 5) -> list[dict]:
|
||||
"""Найти реальные цены на материал/оборудование из двух источников:
|
||||
конъюнктурный анализ (КА, рыночные офферы) и прямые материалы смет.
|
||||
|
||||
КА-результат: source='КА', offers (обезличены), price (min/median/max/winner),
|
||||
region, period. Сметный материал: source='смета', price_cur, freq, regions.
|
||||
"""
|
||||
qset = _terms(query)
|
||||
if not qset:
|
||||
return []
|
||||
results = []
|
||||
for it in _load_ka()["items"]:
|
||||
score = len(qset & it["_terms"])
|
||||
if score > 0:
|
||||
results.append((score, {
|
||||
"source": "КА", "name": it.get("name"), "unit": it.get("unit"),
|
||||
"region": it.get("region"), "period": it.get("period"),
|
||||
"price": it.get("price"), "offers": it.get("offers"),
|
||||
}))
|
||||
for m in _load_estimates().get("materials", []):
|
||||
score = len(qset & m["_terms"])
|
||||
if score > 0:
|
||||
results.append((score, {
|
||||
"source": "смета", "name": m.get("name"), "unit": m.get("unit"),
|
||||
"code": m.get("code"), "price_cur": m.get("price_cur"),
|
||||
"freq": m.get("freq"), "regions": m.get("regions"),
|
||||
}))
|
||||
results.sort(key=lambda x: x[0], reverse=True)
|
||||
return [r for _, r in results[:top_k]]
|
||||
|
||||
|
||||
def find_in_vor(query: str, top_k: int = 5) -> list[dict]:
|
||||
"""Найти, как реально считали ОБЪЁМ работы (из ведомостей объёмов работ).
|
||||
|
||||
Возвращает: name, unit, freq, qty (min/median/max), regions, formulas
|
||||
(формулы расчёта объёма), sources (ссылки на листы обоснования).
|
||||
"""
|
||||
qset = _terms(query)
|
||||
if not qset:
|
||||
return []
|
||||
results = []
|
||||
for it in _load_vor()["items"]:
|
||||
score = len(qset & it["_terms"])
|
||||
if score > 0:
|
||||
results.append((score, it["freq"], it))
|
||||
results.sort(key=lambda x: (x[0], x[1]), reverse=True)
|
||||
keys = ("name", "unit", "freq", "qty", "regions", "formulas", "sources")
|
||||
return [{k: it.get(k) for k in keys} for _, _, it in results[:top_k]]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
qy = " ".join(sys.argv[1:]) or "армирование бетона"
|
||||
for r in find_in_real_estimates(qy):
|
||||
print(f"[{r['code'] or '—'}] {r['name']} ({r['unit']}) — {r['freq']}× {r['regions']}")
|
||||
@@ -0,0 +1,178 @@
|
||||
"""build_ka_index — индекс конъюнктурного анализа (КА) цен из zip-прайсов.
|
||||
|
||||
Источник: 3.Прайс/*.zip, внутри каждого — КА-смета в .gge (схема
|
||||
MarketAnalysis-3_01.xsd) + PDF коммерческих предложений. Извлекаем из .gge
|
||||
структурные цены: материал → офферы поставщиков → цена/регион/квартал →
|
||||
победитель. PDF не трогаем (цены уже в XML).
|
||||
|
||||
КА — самая трудоёмкая часть сметы (3 прайса на каждый материал). Этот индекс
|
||||
даёт ассистенту «материал → реальная рыночная цена с разбросом по поставщикам».
|
||||
|
||||
Обезличивание: поставщики → «Поставщик N» (ordinal), вычищаем CompanyName,
|
||||
ИНН, КПП, сайт, склад, OfferCode (содержит ИНН), имя PDF, ObjectName, ФИО.
|
||||
Остаются техника+цена: материал, ед.изм, цена(ы), регион, квартал, победитель.
|
||||
|
||||
Запуск:
|
||||
python3 scripts/build_ka_index.py "<путь к базе>" [--out data/real_corpus]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
import sys
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from gge_tools import _decode_zip_name # noqa: E402
|
||||
from gge_deep import scrub # noqa: E402 единый обезличиватель (960-06, пикеты, имя проекта)
|
||||
|
||||
MAX_OFFERS = 8 # храним до 8 офферов на материал (показать разброс)
|
||||
|
||||
|
||||
def _txt(el, path: str) -> str:
|
||||
node = el.find(path)
|
||||
return (node.text or "").strip() if node is not None and node.text else ""
|
||||
|
||||
|
||||
def _fnum(s: str) -> float:
|
||||
try:
|
||||
return float(s)
|
||||
except (ValueError, TypeError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _parse_ka_gge(data: bytes) -> list[dict]:
|
||||
"""Разобрать КА .gge → список материалов с обезличенными офферами."""
|
||||
try:
|
||||
root = ET.fromstring(data)
|
||||
except ET.ParseError:
|
||||
return []
|
||||
items = []
|
||||
for item in root.iter("Item"):
|
||||
name = scrub(_txt(item, "Name"))
|
||||
if not name:
|
||||
continue
|
||||
unit = _txt(item, "Unit")
|
||||
mtype = _txt(item, "Type")
|
||||
offers = []
|
||||
for n, off in enumerate(item.findall("Offer"), 1):
|
||||
price_unit = _fnum(_txt(off, "OfferPrice/OfferUnitWithoutVAT")) \
|
||||
or _fnum(_txt(off, "OfferPrice/OfferWithoutVAT"))
|
||||
price_vat = _fnum(_txt(off, "OfferPrice/OfferWithVAT"))
|
||||
region = _txt(off, "Region/Name")
|
||||
year = _txt(off, "OfferDate/Year")
|
||||
quarter = _txt(off, "OfferDate/Quarter")
|
||||
winner = _txt(off, "Winner").lower() == "true"
|
||||
country = _txt(off, "OriginCountry")
|
||||
if price_unit <= 0:
|
||||
continue
|
||||
offers.append({
|
||||
"vendor": f"Поставщик {n}", # обезличено
|
||||
"price": round(price_unit, 2),
|
||||
"price_vat": round(price_vat, 2) if price_vat else None,
|
||||
"region": region,
|
||||
"period": f"{year} Q{quarter}" if year and quarter else year,
|
||||
"country": country,
|
||||
"winner": winner,
|
||||
})
|
||||
if offers:
|
||||
items.append({"name": name, "unit": unit, "type": mtype, "offers": offers})
|
||||
return items
|
||||
|
||||
|
||||
def build(price_dir: Path, out_dir: Path) -> dict:
|
||||
agg: dict[str, dict] = {}
|
||||
n_zip = n_items = n_no_gge = 0
|
||||
regions_seen: set[str] = set()
|
||||
periods_seen: set[str] = set()
|
||||
|
||||
for zp in sorted(price_dir.glob("*.zip")):
|
||||
n_zip += 1
|
||||
try:
|
||||
z = zipfile.ZipFile(zp)
|
||||
except zipfile.BadZipFile:
|
||||
continue
|
||||
gge_infos = [i for i in z.infolist()
|
||||
if _decode_zip_name(i).lower().endswith(".gge")]
|
||||
if not gge_infos:
|
||||
n_no_gge += 1
|
||||
continue
|
||||
for gi in gge_infos:
|
||||
for mat in _parse_ka_gge(z.read(gi)):
|
||||
n_items += 1
|
||||
key = mat["name"].lower()
|
||||
rec = agg.get(key)
|
||||
if rec is None:
|
||||
rec = agg[key] = {
|
||||
"name": mat["name"], "unit": mat["unit"],
|
||||
"type": mat["type"], "offers": [],
|
||||
"regions": defaultdict(int), "periods": defaultdict(int),
|
||||
}
|
||||
for o in mat["offers"]:
|
||||
if o["region"]:
|
||||
rec["regions"][o["region"]] += 1
|
||||
regions_seen.add(o["region"])
|
||||
if o["period"]:
|
||||
rec["periods"][o["period"]] += 1
|
||||
periods_seen.add(o["period"])
|
||||
if len(rec["offers"]) < MAX_OFFERS:
|
||||
rec["offers"].append(o)
|
||||
|
||||
items = []
|
||||
for rec in agg.values():
|
||||
prices = [o["price"] for o in rec["offers"] if o["price"] > 0]
|
||||
winner = next((o["price"] for o in rec["offers"] if o["winner"]), None)
|
||||
pstat = {}
|
||||
if prices:
|
||||
pstat = {
|
||||
"min": round(min(prices), 2),
|
||||
"median": round(statistics.median(prices), 2),
|
||||
"max": round(max(prices), 2),
|
||||
"winner": winner,
|
||||
}
|
||||
regs = sorted(rec["regions"], key=rec["regions"].get, reverse=True)
|
||||
pers = sorted(rec["periods"], key=rec["periods"].get, reverse=True)
|
||||
items.append({
|
||||
"name": rec["name"], "unit": rec["unit"], "type": rec["type"],
|
||||
"region": regs[0] if regs else "",
|
||||
"period": pers[0] if pers else "",
|
||||
"offers": rec["offers"], "price": pstat,
|
||||
})
|
||||
items.sort(key=lambda x: len(x["offers"]), reverse=True)
|
||||
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
index = {
|
||||
"meta": {
|
||||
"zip_files": n_zip, "zip_without_gge": n_no_gge,
|
||||
"ka_items_raw": n_items, "unique_materials": len(items),
|
||||
"regions": sorted(regions_seen), "periods": sorted(periods_seen),
|
||||
},
|
||||
"items": items,
|
||||
}
|
||||
(out_dir / "ka_index.json").write_text(
|
||||
json.dumps(index, ensure_ascii=False), encoding="utf-8")
|
||||
return index["meta"]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("base")
|
||||
ap.add_argument("--out", default="data/real_corpus")
|
||||
args = ap.parse_args()
|
||||
price_dir = Path(args.base) / "3.Прайс"
|
||||
if not price_dir.exists():
|
||||
print(f"Не найдено 3.Прайс в {args.base}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
out = Path(args.out)
|
||||
if not out.is_absolute():
|
||||
out = Path(__file__).resolve().parent.parent / out
|
||||
meta = build(price_dir, out)
|
||||
print(json.dumps(meta, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,195 @@
|
||||
"""build_real_corpus — обогащённый индекс реальных смет (ЛСР/ОСР) из .gge.
|
||||
|
||||
Через gge_deep вытаскивает ВСЁ ценное по каждой расценке: ресурсный состав
|
||||
(рабочие/машины/материалы с нормами расхода и ценами), трудозатраты,
|
||||
цену/ед (текущую), накладные/прибыль с обоснованиями, коэффициенты, уровни
|
||||
цен. Дедуп по коду расценки: состав берём из самого полного вхождения,
|
||||
freq/qty/регионы агрегируем по всем. Прямые материалы (Item/Material) идут
|
||||
отдельными искомыми позициями с ценой.
|
||||
|
||||
Обезличивание: gge_deep.scrub чистит проект-токены (имя проекта, код 960-06,
|
||||
пикеты ПК); реквизиты/ФИО не извлекаются вовсе.
|
||||
|
||||
Запуск: python3 scripts/build_real_corpus.py "<путь к базе>" [--out data/real_corpus]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from gge_deep import parse_estimate_full, scrub # noqa: E402
|
||||
|
||||
MAX_RES = 30 # лимит ресурсов каждого типа в карточке
|
||||
|
||||
|
||||
def _norm_set(code: str) -> str:
|
||||
c = (code or "").upper()
|
||||
return "ОСР" if c.startswith("ОС") else "ЛСР"
|
||||
|
||||
|
||||
def _scrub_resources(res: dict) -> dict:
|
||||
for lst in res.values():
|
||||
for r in lst:
|
||||
if r.get("name"):
|
||||
r["name"] = scrub(r["name"])
|
||||
return {k: v[:MAX_RES] for k, v in res.items()}
|
||||
|
||||
|
||||
def build(root: Path, out_dir: Path) -> dict:
|
||||
agg: dict[str, dict] = {}
|
||||
mat_agg: dict[str, dict] = {}
|
||||
n_files = n_pos = n_err = n_mat = 0
|
||||
regions_seen: set[str] = set()
|
||||
|
||||
for f in sorted(root.rglob("*.gge")):
|
||||
data = parse_estimate_full(f)
|
||||
n_files += 1
|
||||
if "error" in data:
|
||||
n_err += 1
|
||||
continue
|
||||
region = data.get("region", "")
|
||||
if region:
|
||||
regions_seen.add(region)
|
||||
nset = _norm_set(data.get("code", ""))
|
||||
est_code = scrub(data.get("code", ""))
|
||||
|
||||
for p in data["positions"]:
|
||||
name = scrub(p["name"])
|
||||
if not name:
|
||||
continue
|
||||
n_pos += 1
|
||||
code = p["code"]
|
||||
key = code if code else f"~{name.lower()}"
|
||||
rec = agg.get(key)
|
||||
if rec is None:
|
||||
rec = agg[key] = {
|
||||
"code": code, "names": defaultdict(int), "units": defaultdict(int),
|
||||
"prefix": p["prefix"], "kind": p.get("kind", "cost"),
|
||||
"norm_sets": defaultdict(int),
|
||||
"regions": defaultdict(int), "qtys": [], "examples": [],
|
||||
"freq": 0, "_best_res": -1,
|
||||
# обогащённые поля (из самого полного вхождения)
|
||||
"unit_cost_cur": 0.0, "labor_ch": 0.0, "machinist_ch": 0.0,
|
||||
"price_base": "", "price_cur": "",
|
||||
"overhead": None, "profit": None, "coefficients": [],
|
||||
"resources": {"workers": [], "machines": [], "materials": []},
|
||||
}
|
||||
rec["names"][name] += 1
|
||||
if p["unit"]:
|
||||
rec["units"][p["unit"]] += 1
|
||||
rec["norm_sets"][nset] += 1
|
||||
if region:
|
||||
rec["regions"][region] += 1
|
||||
if p["quantity"] > 0:
|
||||
rec["qtys"].append(p["quantity"])
|
||||
rec["freq"] += 1
|
||||
if len(rec["examples"]) < 3 and est_code:
|
||||
rec["examples"].append({"est": est_code, "qty": p["quantity"], "unit": p["unit"]})
|
||||
# состав — из вхождения с максимумом ресурсов
|
||||
res = p["resources"]
|
||||
res_n = len(res["workers"]) + len(res["machines"]) + len(res["materials"])
|
||||
if res_n > rec["_best_res"]:
|
||||
rec["_best_res"] = res_n
|
||||
rec["unit_cost_cur"] = p["unit_cost_cur"]
|
||||
rec["labor_ch"] = p["labor_ch"]
|
||||
rec["machinist_ch"] = p["machinist_ch"]
|
||||
rec["price_base"] = data.get("price_base", "")
|
||||
rec["price_cur"] = data.get("price_cur", "")
|
||||
rec["overhead"] = p["overhead"]
|
||||
rec["profit"] = p["profit"]
|
||||
rec["coefficients"] = p["coefficients"][:5]
|
||||
rec["resources"] = _scrub_resources(res)
|
||||
|
||||
for m in data.get("direct_materials", []):
|
||||
name = scrub(m["name"])
|
||||
if not name:
|
||||
continue
|
||||
n_mat += 1
|
||||
key = name.lower()
|
||||
mr = mat_agg.get(key)
|
||||
if mr is None:
|
||||
mr = mat_agg[key] = {"name": name, "code": m["code"],
|
||||
"unit": m["unit"], "prices": [], "freq": 0,
|
||||
"regions": defaultdict(int)}
|
||||
if m["price_cur"] > 0:
|
||||
mr["prices"].append(m["price_cur"])
|
||||
if region:
|
||||
mr["regions"][region] += 1
|
||||
mr["freq"] += 1
|
||||
|
||||
# финализация расценок
|
||||
items = []
|
||||
for rec in agg.values():
|
||||
qtys = rec["qtys"]
|
||||
qstat = {"min": round(min(qtys), 3), "median": round(statistics.median(qtys), 3),
|
||||
"max": round(max(qtys), 3)} if qtys else {}
|
||||
items.append({
|
||||
"code": rec["code"],
|
||||
"name": max(rec["names"].items(), key=lambda kv: kv[1])[0],
|
||||
"unit": max(rec["units"].items(), key=lambda kv: kv[1])[0] if rec["units"] else "",
|
||||
"prefix": rec["prefix"],
|
||||
"kind": rec["kind"],
|
||||
"freq": rec["freq"],
|
||||
"norm_sets": sorted(rec["norm_sets"], key=rec["norm_sets"].get, reverse=True),
|
||||
"regions": sorted(rec["regions"], key=rec["regions"].get, reverse=True)[:5],
|
||||
"qty": qstat,
|
||||
"unit_cost_cur": rec["unit_cost_cur"],
|
||||
"labor_ch": rec["labor_ch"], "machinist_ch": rec["machinist_ch"],
|
||||
"price_base": rec["price_base"], "price_cur": rec["price_cur"],
|
||||
"overhead": rec["overhead"], "profit": rec["profit"],
|
||||
"coefficients": rec["coefficients"],
|
||||
"resources": rec["resources"],
|
||||
"examples": rec["examples"],
|
||||
})
|
||||
items.sort(key=lambda x: x["freq"], reverse=True)
|
||||
|
||||
# финализация прямых материалов
|
||||
materials = []
|
||||
for mr in mat_agg.values():
|
||||
pr = mr["prices"]
|
||||
materials.append({
|
||||
"name": mr["name"], "code": mr["code"], "unit": mr["unit"],
|
||||
"freq": mr["freq"],
|
||||
"price_cur": round(statistics.median(pr), 2) if pr else 0.0,
|
||||
"regions": sorted(mr["regions"], key=mr["regions"].get, reverse=True)[:3],
|
||||
})
|
||||
materials.sort(key=lambda x: x["freq"], reverse=True)
|
||||
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
index = {
|
||||
"meta": {
|
||||
"files_parsed": n_files, "parse_errors": n_err,
|
||||
"positions_total": n_pos, "unique_items": len(items),
|
||||
"direct_materials_total": n_mat, "unique_materials": len(materials),
|
||||
"regions": sorted(regions_seen),
|
||||
},
|
||||
"items": items,
|
||||
"materials": materials,
|
||||
}
|
||||
(out_dir / "estimates_index.json").write_text(
|
||||
json.dumps(index, ensure_ascii=False), encoding="utf-8")
|
||||
return index["meta"]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("base")
|
||||
ap.add_argument("--out", default="data/real_corpus")
|
||||
args = ap.parse_args()
|
||||
root = Path(args.base) / "2.Сметы"
|
||||
if not root.exists():
|
||||
print(f"Не найдено 2.Сметы в {args.base}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
out = Path(args.out)
|
||||
if not out.is_absolute():
|
||||
out = Path(__file__).resolve().parent.parent / out
|
||||
print(json.dumps(build(root, out), ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,119 @@
|
||||
"""build_vor_index — индекс ведомостей объёмов работ (ВОР, QuantityTakeoff).
|
||||
|
||||
ВОР отвечает на вопрос «как считали ОБЪЁМ работы»: работа → ед → кол-во →
|
||||
формула расчёта → ссылка на лист обоснования. Дедуп по имени работы (у ВОР
|
||||
нет кода расценки). Источник: 4.ВОР/**/*.gge (схема QuantityTakeoff-3_01).
|
||||
|
||||
Обезличивание: gge_deep.scrub (код проекта 960-06, пикеты, имя объекта);
|
||||
ФИО подписантов не извлекаются.
|
||||
|
||||
Запуск: python3 scripts/build_vor_index.py "<путь к базе>" [--out data/real_corpus]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from gge_deep import parse_vor, scrub # noqa: E402
|
||||
|
||||
def _region_from_section(section: str) -> str:
|
||||
s = (section or "").lower()
|
||||
if "тверск" in s:
|
||||
return "Тверская область"
|
||||
if "московск" in s or "москва" in s:
|
||||
return "Московская область"
|
||||
return ""
|
||||
|
||||
|
||||
def build(root: Path, out_dir: Path) -> dict:
|
||||
agg: dict[str, dict] = {}
|
||||
n_files = n_works = n_err = 0
|
||||
regions_seen: set[str] = set()
|
||||
|
||||
for f in sorted(root.rglob("*.gge")):
|
||||
data = parse_vor(f)
|
||||
n_files += 1
|
||||
if "error" in data:
|
||||
n_err += 1
|
||||
continue
|
||||
for w in data["works"]:
|
||||
name = scrub(w["name"])
|
||||
if not name:
|
||||
continue
|
||||
n_works += 1
|
||||
key = name.lower()
|
||||
rec = agg.get(key)
|
||||
if rec is None:
|
||||
rec = agg[key] = {
|
||||
"name": name, "units": defaultdict(int), "qtys": [],
|
||||
"formulas": [], "sources": [], "regions": defaultdict(int),
|
||||
"freq": 0,
|
||||
}
|
||||
if w["unit"]:
|
||||
rec["units"][w["unit"]] += 1
|
||||
if w["quantity"] > 0:
|
||||
rec["qtys"].append(w["quantity"])
|
||||
rec["freq"] += 1
|
||||
region = _region_from_section(w["section"])
|
||||
if region:
|
||||
rec["regions"][region] += 1
|
||||
regions_seen.add(region)
|
||||
formula = scrub(w["formula"])
|
||||
if formula and len(rec["formulas"]) < 3 and formula not in rec["formulas"]:
|
||||
rec["formulas"].append(formula[:200])
|
||||
source = scrub(w["source"])
|
||||
if source and len(rec["sources"]) < 3 and source not in rec["sources"]:
|
||||
rec["sources"].append(source[:120])
|
||||
|
||||
items = []
|
||||
for rec in agg.values():
|
||||
qtys = rec["qtys"]
|
||||
qstat = {"min": round(min(qtys), 3), "median": round(statistics.median(qtys), 3),
|
||||
"max": round(max(qtys), 3)} if qtys else {}
|
||||
items.append({
|
||||
"name": rec["name"],
|
||||
"unit": max(rec["units"].items(), key=lambda kv: kv[1])[0] if rec["units"] else "",
|
||||
"freq": rec["freq"],
|
||||
"qty": qstat,
|
||||
"regions": sorted(rec["regions"], key=rec["regions"].get, reverse=True)[:5],
|
||||
"formulas": rec["formulas"],
|
||||
"sources": rec["sources"],
|
||||
})
|
||||
items.sort(key=lambda x: x["freq"], reverse=True)
|
||||
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
index = {
|
||||
"meta": {
|
||||
"files_parsed": n_files, "parse_errors": n_err,
|
||||
"works_total": n_works, "unique_works": len(items),
|
||||
"regions": sorted(regions_seen),
|
||||
},
|
||||
"items": items,
|
||||
}
|
||||
(out_dir / "vor_index.json").write_text(
|
||||
json.dumps(index, ensure_ascii=False), encoding="utf-8")
|
||||
return index["meta"]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("base")
|
||||
ap.add_argument("--out", default="data/real_corpus")
|
||||
args = ap.parse_args()
|
||||
root = Path(args.base) / "4.ВОР"
|
||||
if not root.exists():
|
||||
print(f"Не найдено 4.ВОР в {args.base}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
out = Path(args.out)
|
||||
if not out.is_absolute():
|
||||
out = Path(__file__).resolve().parent.parent / out
|
||||
print(json.dumps(build(root, out), ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,211 @@
|
||||
"""verify_corpus — доказательная проверка индекса реальных смет.
|
||||
|
||||
Три проверки (как просил пользователь — «принудительный поиск, как будто
|
||||
знаешь что искать»):
|
||||
1. Обезличивание: проект-токены в индексе == 0 (по границе слова).
|
||||
2. Hand-crafted known-answer: реалистичные запросы естественным языком
|
||||
(другая словоформа) → ожидаемая расценка обязана быть в топ-5.
|
||||
3. Авто recall@5: по выборке позиций строим запрос из их же названия
|
||||
и меряем долю, где позиция вернулась в топ-5.
|
||||
|
||||
Exit code != 0 если обезличивание нарушено или hand-crafted < 100%.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
import real_corpus as rc # noqa: E402
|
||||
|
||||
_ROOT = Path(__file__).resolve().parent.parent / "data" / "real_corpus"
|
||||
INDEX = _ROOT / "estimates_index.json"
|
||||
KA_INDEX = _ROOT / "ka_index.json"
|
||||
VOR_INDEX = _ROOT / "vor_index.json"
|
||||
|
||||
# Единый набор проект-токенов (имя/код проекта, пикеты, ФИО) для всех индексов.
|
||||
# Проект идентифицирует МАРШРУТ «Санкт-Петербург – Москва» (с тире), а не город
|
||||
# «Санкт-Петербург» — последний легитимен как регион поставщика в КА.
|
||||
PROJECT_LEAKS = [r"\bРИМ\b", r"ВСМ", r"Крюков", r"Алабушев", r"высокоскоростн",
|
||||
r"Санкт-Петербург\s*[–-]\s*Москва", r"ВОХР", r"GUID",
|
||||
r"Серенькая", r"960-06", r"ПК ?\d+\+", r"Нов\w*\s+Тверь"]
|
||||
|
||||
# Проект-идентификаторы: в обезличенном индексе их быть не должно (граница слова).
|
||||
LEAK_PATTERNS = PROJECT_LEAKS
|
||||
|
||||
# Запросы естественным языком (НЕ дословно из индекса) → ожидаемая расценка.
|
||||
# Каждый ответ заранее проверен как присутствующий в корпусе.
|
||||
KNOWN_ANSWERS = [
|
||||
("армировать бетонные слои", "06-03-004-14"),
|
||||
("устройство бетонной подготовки", "06-01-001-01"),
|
||||
("доставить металлоконструкции автомобилем", "30-08-122-05"),
|
||||
("засыпать траншеи вручную грунтом", "01-02-061-01"),
|
||||
("укрепление откосов монолитным бетоном", "01-02-046-05"),
|
||||
("асфальтобетонные дорожки и тротуары", "27-07-001-01"),
|
||||
("обмазочная битумная гидроизоляция", "08-01-003-07"),
|
||||
]
|
||||
|
||||
|
||||
def check_anonymization() -> bool:
|
||||
raw = INDEX.read_text(encoding="utf-8")
|
||||
ok = True
|
||||
print("1) ОБЕЗЛИЧИВАНИЕ (ожидаем 0 по каждому):")
|
||||
for pat in LEAK_PATTERNS:
|
||||
n = len(re.findall(pat, raw))
|
||||
flag = "OK" if n == 0 else "!! УТЕЧКА"
|
||||
if n:
|
||||
ok = False
|
||||
print(f" {pat:22} = {n} {flag}")
|
||||
return ok
|
||||
|
||||
|
||||
def check_known_answers() -> bool:
|
||||
print("\n2) HAND-CRAFTED KNOWN-ANSWER (ожидаем ранг в топ-5):")
|
||||
hits = 0
|
||||
for query, expect in KNOWN_ANSWERS:
|
||||
res = rc.find_in_real_estimates(query, top_k=5)
|
||||
codes = [r["code"] for r in res]
|
||||
rank = codes.index(expect) + 1 if expect in codes else None
|
||||
ok = rank is not None
|
||||
hits += ok
|
||||
top = f"#{rank}" if ok else "НЕ НАЙДЕНО"
|
||||
head = res[0]["name"][:42] if res else "—"
|
||||
print(f" «{query[:38]:38}» → [{expect}] {top:11} (топ-1: {head})")
|
||||
print(f" ИТОГ: {hits}/{len(KNOWN_ANSWERS)}")
|
||||
return hits == len(KNOWN_ANSWERS)
|
||||
|
||||
|
||||
def check_auto_recall(sample: int = 200) -> float:
|
||||
data = json.loads(INDEX.read_text(encoding="utf-8"))
|
||||
items = [it for it in data["items"] if it.get("code")]
|
||||
step = max(1, len(items) // sample)
|
||||
chosen = items[::step][:sample]
|
||||
hits = 0
|
||||
for it in chosen:
|
||||
# запрос из 3 значимых слов названия (>3 букв), как набрал бы человек
|
||||
words = [w for w in re.split(r"\W+", it["name"]) if len(w) > 3][:3]
|
||||
if not words:
|
||||
continue
|
||||
res = rc.find_in_real_estimates(" ".join(words), top_k=5)
|
||||
if it["code"] in [r["code"] for r in res]:
|
||||
hits += 1
|
||||
pct = 100.0 * hits / len(chosen) if chosen else 0.0
|
||||
print(f"\n3) АВТО recall@5 по {len(chosen)} позициям: {hits}/{len(chosen)} = {pct:.1f}%")
|
||||
return pct
|
||||
|
||||
|
||||
# === КА (цены) ===
|
||||
|
||||
# Утечки поставщиков: ИНН/КПП как 10-12-значные числа, сайты, имена полей.
|
||||
KA_LEAK_PATTERNS = [r'"\d{10,12}"', r"www\.", r"\.ru/", r"CompanyName",
|
||||
r"OfferCode", r"StorePlace", r"<INN>"] + PROJECT_LEAKS
|
||||
|
||||
# Запросы естественным языком → фрагмент имени материала, который обязан
|
||||
# быть в топ-5 (ответ заранее проверен как присутствующий в КА-корпусе).
|
||||
KA_KNOWN = [
|
||||
("металлический шкаф для одежды односекционный", "Односекционный металлический шкаф"),
|
||||
("датчик температуры накладной", "Датчик температуры накладной"),
|
||||
("термометр биметаллический", "Термометр биметаллический"),
|
||||
("манометр с трубчатой пружиной", "Манометр деформационный"),
|
||||
("магнитный извещатель", "Магнитный извещатель"),
|
||||
("датчик протечки воды", "Датчик протечки воды"),
|
||||
]
|
||||
|
||||
|
||||
def check_ka_anonymization() -> bool:
|
||||
if not KA_INDEX.exists():
|
||||
print("\n4) КА-индекс отсутствует — пропуск")
|
||||
return True
|
||||
raw = KA_INDEX.read_text(encoding="utf-8")
|
||||
ok = True
|
||||
print("\n4) КА ОБЕЗЛИЧИВАНИЕ (ожидаем 0 по каждому):")
|
||||
for pat in KA_LEAK_PATTERNS:
|
||||
n = len(re.findall(pat, raw))
|
||||
if n:
|
||||
ok = False
|
||||
print(f" {pat:16} = {n} {'OK' if n == 0 else '!! УТЕЧКА'}")
|
||||
return ok
|
||||
|
||||
|
||||
def check_ka_known() -> bool:
|
||||
if not KA_INDEX.exists():
|
||||
return True
|
||||
print("\n5) КА HAND-CRAFTED KNOWN-ANSWER (фрагмент в топ-5):")
|
||||
hits = 0
|
||||
for query, frag in KA_KNOWN:
|
||||
res = rc.find_ka_price(query, top_k=5)
|
||||
found = next((i + 1 for i, r in enumerate(res)
|
||||
if frag.lower() in (r["name"] or "").lower()), None)
|
||||
hits += found is not None
|
||||
price = res[0]["price"].get("winner") if res and res[0].get("price") else "—"
|
||||
rank = f"#{found}" if found else "НЕ НАЙДЕНО"
|
||||
print(f" «{query[:34]:34}» → {rank:11} (топ-1 winner-цена: {price})")
|
||||
print(f" ИТОГ: {hits}/{len(KA_KNOWN)}")
|
||||
return hits == len(KA_KNOWN)
|
||||
|
||||
|
||||
# === ВОР (объёмы) ===
|
||||
|
||||
VOR_KNOWN = [
|
||||
("разработка грунта экскаватором", "разработка"),
|
||||
("снятие почвенно-растительного слоя", "снятие"),
|
||||
("устройство монолитного бетона", "монолитн"),
|
||||
("погрузка грунта", "погрузка"),
|
||||
]
|
||||
|
||||
|
||||
def check_vor_anonymization() -> bool:
|
||||
if not VOR_INDEX.exists():
|
||||
print("\n6) ВОР-индекс отсутствует — пропуск")
|
||||
return True
|
||||
raw = VOR_INDEX.read_text(encoding="utf-8")
|
||||
ok = True
|
||||
print("\n6) ВОР ОБЕЗЛИЧИВАНИЕ (ожидаем 0):")
|
||||
for pat in PROJECT_LEAKS:
|
||||
n = len(re.findall(pat, raw))
|
||||
if n:
|
||||
ok = False
|
||||
print(f" {pat:16} = {n} {'OK' if n == 0 else '!! УТЕЧКА'}")
|
||||
return ok
|
||||
|
||||
|
||||
def check_vor_known() -> bool:
|
||||
if not VOR_INDEX.exists():
|
||||
return True
|
||||
print("\n7) ВОР HAND-CRAFTED KNOWN-ANSWER (фрагмент в топ-5):")
|
||||
hits = 0
|
||||
for query, frag in VOR_KNOWN:
|
||||
res = rc.find_in_vor(query, top_k=5)
|
||||
found = next((i + 1 for i, r in enumerate(res)
|
||||
if frag.lower() in (r["name"] or "").lower()), None)
|
||||
hits += found is not None
|
||||
qty = res[0]["qty"].get("median") if res and res[0].get("qty") else "—"
|
||||
print(f" «{query[:32]:32}» → {('#'+str(found)) if found else 'НЕ НАЙДЕНО':11} (топ-1 медиана объёма: {qty})")
|
||||
print(f" ИТОГ: {hits}/{len(VOR_KNOWN)}")
|
||||
return hits == len(VOR_KNOWN)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
anon_ok = check_anonymization()
|
||||
known_ok = check_known_answers()
|
||||
recall = check_auto_recall()
|
||||
ka_anon_ok = check_ka_anonymization()
|
||||
ka_known_ok = check_ka_known()
|
||||
vor_anon_ok = check_vor_anonymization()
|
||||
vor_known_ok = check_vor_known()
|
||||
print("\n=== ВЕРДИКТ ===")
|
||||
print(f" сметы обезличивание: {'ЧИСТО' if anon_ok else 'НАРУШЕНО'}")
|
||||
print(f" сметы known-answer: {'100%' if known_ok else 'НЕ 100%'}")
|
||||
print(f" сметы авто recall@5: {recall:.1f}%")
|
||||
print(f" КА обезличивание: {'ЧИСТО' if ka_anon_ok else 'НАРУШЕНО'}")
|
||||
print(f" КА known-answer: {'100%' if ka_known_ok else 'НЕ 100%'}")
|
||||
print(f" ВОР обезличивание: {'ЧИСТО' if vor_anon_ok else 'НАРУШЕНО'}")
|
||||
print(f" ВОР known-answer: {'100%' if vor_known_ok else 'НЕ 100%'}")
|
||||
ok = all([anon_ok, known_ok, ka_anon_ok, ka_known_ok, vor_anon_ok, vor_known_ok])
|
||||
sys.exit(0 if ok else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -112,6 +112,46 @@ def tool_find_in_normative(*, query: str, top_k: int = 3) -> dict:
|
||||
return {"query": query, "result": text or "(нет совпадений)"}
|
||||
|
||||
|
||||
def tool_find_in_real_estimates(*, query: str, top_k: int = 5) -> dict:
|
||||
"""Поиск по обезличенному корпусу РЕАЛЬНЫХ применённых смет (ЛСР/ОСР).
|
||||
Деградирует в error, если индекс не задеплоен."""
|
||||
try:
|
||||
from real_corpus import find_in_real_estimates
|
||||
except Exception as e:
|
||||
return {"query": query, "error": f"Корпус недоступен: {type(e).__name__}: {e}"}
|
||||
try:
|
||||
hits = find_in_real_estimates(query, top_k=top_k)
|
||||
except Exception as e:
|
||||
return {"query": query, "error": f"Ошибка поиска: {type(e).__name__}: {e}"}
|
||||
return {"query": query, "count": len(hits), "results": hits}
|
||||
|
||||
|
||||
def tool_find_ka_price(*, query: str, top_k: int = 5) -> dict:
|
||||
"""Поиск реальных цен материала (КА-рынок + прямые материалы смет), обезличено."""
|
||||
try:
|
||||
from real_corpus import find_ka_price
|
||||
except Exception as e:
|
||||
return {"query": query, "error": f"КА-индекс недоступен: {type(e).__name__}: {e}"}
|
||||
try:
|
||||
hits = find_ka_price(query, top_k=top_k)
|
||||
except Exception as e:
|
||||
return {"query": query, "error": f"Ошибка поиска: {type(e).__name__}: {e}"}
|
||||
return {"query": query, "count": len(hits), "results": hits}
|
||||
|
||||
|
||||
def tool_find_in_vor(*, query: str, top_k: int = 5) -> dict:
|
||||
"""Поиск по ведомостям объёмов работ — как реально считали объём."""
|
||||
try:
|
||||
from real_corpus import find_in_vor
|
||||
except Exception as e:
|
||||
return {"query": query, "error": f"ВОР-индекс недоступен: {type(e).__name__}: {e}"}
|
||||
try:
|
||||
hits = find_in_vor(query, top_k=top_k)
|
||||
except Exception as e:
|
||||
return {"query": query, "error": f"Ошибка поиска: {type(e).__name__}: {e}"}
|
||||
return {"query": query, "count": len(hits), "results": hits}
|
||||
|
||||
|
||||
def tool_list_files() -> dict:
|
||||
user, tab = _user_tab()
|
||||
work_dir = _work_dir(user, tab)
|
||||
@@ -293,6 +333,63 @@ TOOLS: dict[str, dict] = {
|
||||
"required": ["query"],
|
||||
},
|
||||
},
|
||||
"find_in_real_estimates": {
|
||||
"fn": tool_find_in_real_estimates,
|
||||
"description": (
|
||||
"Поиск по корпусу РЕАЛЬНЫХ применённых смет сданного проекта "
|
||||
"(обезличено). По описанию работы возвращает: какую расценку "
|
||||
"реально применяли эксперты, ед.изм, как часто (freq), типовой "
|
||||
"объём (qty min/median/max), регионы. Дополняет find_in_normative: "
|
||||
"тот говорит «какие расценки существуют», этот — «какие реально "
|
||||
"применяли под эту работу». Используй когда нужно подсказать "
|
||||
"расценку под работу или показать реальную практику применения."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": "string", "description": "Описание работы на русском (напр. «армирование монолитной плиты»)"},
|
||||
"top_k": {"type": "integer", "description": "Кол-во результатов (default 5)"},
|
||||
},
|
||||
"required": ["query"],
|
||||
},
|
||||
},
|
||||
"find_ka_price": {
|
||||
"fn": tool_find_ka_price,
|
||||
"description": (
|
||||
"Поиск реальных рыночных цен на материал/оборудование из "
|
||||
"конъюнктурного анализа (КА) сданного проекта (обезличено: "
|
||||
"поставщики → «Поставщик N»). Возвращает: цену min/median/max, "
|
||||
"цену победителя, разброс по обезличенным офферам, регион, "
|
||||
"квартал/год. Используй для обоснования цены материала или когда "
|
||||
"нужен реальный рыночный ориентир, а не нормативная цена ФССЦ."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": "string", "description": "Название материала/оборудования (напр. «датчик температуры накладной»)"},
|
||||
"top_k": {"type": "integer", "description": "Кол-во результатов (default 5)"},
|
||||
},
|
||||
"required": ["query"],
|
||||
},
|
||||
},
|
||||
"find_in_vor": {
|
||||
"fn": tool_find_in_vor,
|
||||
"description": (
|
||||
"Поиск по ведомостям объёмов работ (ВОР) сданного проекта "
|
||||
"(обезличено). По описанию работы возвращает: как реально считали "
|
||||
"ОБЪЁМ — ед.изм, типовое кол-во (min/median/max), формулы расчёта "
|
||||
"объёма, ссылки на листы обоснования. Используй когда вопрос про "
|
||||
"объём работ, методику его подсчёта или ведомость объёмов."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": "string", "description": "Описание работы (напр. «разработка грунта экскаватором»)"},
|
||||
"top_k": {"type": "integer", "description": "Кол-во результатов (default 5)"},
|
||||
},
|
||||
"required": ["query"],
|
||||
},
|
||||
},
|
||||
"list_files": {
|
||||
"fn": tool_list_files,
|
||||
"description": "Список файлов, загруженных пользователем в текущей вкладке чата.",
|
||||
|
||||
@@ -113,12 +113,44 @@ def list_files(user: str, tab_id: str) -> dict:
|
||||
return {"tab_id": tab_id, "files": files}
|
||||
|
||||
|
||||
def _corpus_call(fn_name: str, query: str, top_k: int) -> dict:
|
||||
"""Общий враппер поиска по корпусу реальных смет (real_corpus).
|
||||
Деградирует в error, если индекс не задеплоен (не роняет диалог)."""
|
||||
try:
|
||||
import real_corpus
|
||||
fn = getattr(real_corpus, fn_name)
|
||||
except Exception as e:
|
||||
return {"query": query, "error": f"Корпус недоступен: {type(e).__name__}: {e}"}
|
||||
try:
|
||||
return {"query": query, "results": fn(query, top_k=top_k)}
|
||||
except Exception as e:
|
||||
return {"query": query, "error": f"Ошибка поиска: {type(e).__name__}: {e}"}
|
||||
|
||||
|
||||
def find_in_real_estimates(user: str, tab_id: str, *, query: str, top_k: int = 3) -> dict:
|
||||
"""Реальные применённые расценки (с составом/ценой/накладными) под работу."""
|
||||
return _corpus_call("find_in_real_estimates", query, top_k)
|
||||
|
||||
|
||||
def find_ka_price(user: str, tab_id: str, *, query: str, top_k: int = 5) -> dict:
|
||||
"""Реальные цены материала: рыночный КА + прямые материалы смет."""
|
||||
return _corpus_call("find_ka_price", query, top_k)
|
||||
|
||||
|
||||
def find_in_vor(user: str, tab_id: str, *, query: str, top_k: int = 5) -> dict:
|
||||
"""Как реально считали объём работы (ведомости объёмов работ)."""
|
||||
return _corpus_call("find_in_vor", query, top_k)
|
||||
|
||||
|
||||
# ---------- Registry + JSON-Schema for the API ----------
|
||||
|
||||
TOOL_REGISTRY = {
|
||||
"read_xlsx_sheet": read_xlsx_sheet,
|
||||
"find_in_normative": find_in_normative,
|
||||
"list_files": list_files,
|
||||
"find_in_real_estimates": find_in_real_estimates,
|
||||
"find_ka_price": find_ka_price,
|
||||
"find_in_vor": find_in_vor,
|
||||
}
|
||||
|
||||
TOOLS_SCHEMA = [
|
||||
@@ -177,6 +209,68 @@ TOOLS_SCHEMA = [
|
||||
"parameters": {"type": "object", "properties": {}},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "find_in_real_estimates",
|
||||
"description": (
|
||||
"Поиск по корпусу РЕАЛЬНЫХ применённых смет сданного проекта. "
|
||||
"По описанию работы возвращает реальную расценку с составом "
|
||||
"(рабочие/машины/материалы, нормы расхода), ценой/ед, "
|
||||
"трудозатратами, накладными/прибылью с обоснованием, как часто "
|
||||
"применяли. Дополняет find_in_normative: тот — какие расценки "
|
||||
"бывают, этот — какие реально применяли под эту работу."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": "string", "description": "Описание работы (напр. «армирование монолитной плиты»)"},
|
||||
"top_k": {"type": "integer", "description": "Кол-во результатов (default 3)"},
|
||||
},
|
||||
"required": ["query"],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "find_ka_price",
|
||||
"description": (
|
||||
"Реальные цены на материал/оборудование: рыночный конъюнктурный "
|
||||
"анализ (КА, обезличенные офферы поставщиков + цена победителя) "
|
||||
"и прямые материалы из смет. Используй для обоснования цены "
|
||||
"материала или рыночного ориентира вместо нормативной цены ФССЦ."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": "string", "description": "Название материала (напр. «щебень фракция 20-40»)"},
|
||||
"top_k": {"type": "integer", "description": "Кол-во результатов (default 5)"},
|
||||
},
|
||||
"required": ["query"],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "find_in_vor",
|
||||
"description": (
|
||||
"Поиск по ведомостям объёмов работ (ВОР): как реально считали "
|
||||
"ОБЪЁМ работы — ед.изм, типовое кол-во, формулы расчёта, ссылки "
|
||||
"на листы обоснования. Используй когда вопрос про объём работ "
|
||||
"или методику его подсчёта."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": "string", "description": "Описание работы (напр. «разработка грунта экскаватором»)"},
|
||||
"top_k": {"type": "integer", "description": "Кол-во результатов (default 5)"},
|
||||
},
|
||||
"required": ["query"],
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@@ -195,4 +289,7 @@ def summarize_result(name: str, result: dict) -> str:
|
||||
if name == "list_files":
|
||||
n = len(result.get("files", []))
|
||||
return f"✓ {name}: {n} файлов"
|
||||
if name in ("find_in_real_estimates", "find_ka_price", "find_in_vor"):
|
||||
n = len(result.get("results", []))
|
||||
return f"✓ {name}: запрос «{result.get('query')}» — {n} совпадений"
|
||||
return f"✓ {name}"
|
||||
|
||||
Reference in New Issue
Block a user