356 lines
17 KiB
Python
356 lines
17 KiB
Python
"""Уровень цен в блоке корпуса: price_cur — это уровень, а не «не указан».
|
||
|
||
Red-green: до фикса _search_corpus читал только price_level; в основной части
|
||
корпуса его нет ни у одной записи (уровень лежит в price_cur), поэтому 3092 цены
|
||
из 3097 получали ложное «УРОВЕНЬ ЦЕН НЕ УКАЗАН» и модель отказывалась считать.
|
||
Работает на ЖИВЫХ индексах data/real_corpus/.
|
||
"""
|
||
import json
|
||
import sys
|
||
import types
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).parent.parent
|
||
sys.path.insert(0, str(ROOT))
|
||
|
||
|
||
def _import_with_pymorphy_stub():
|
||
"""search_engine требует pymorphy3 (есть на сервере); локально — стаб только
|
||
на время импорта, чтобы не протечь в real_corpus (у него свой fallback)."""
|
||
try:
|
||
import pymorphy3 # noqa: F401
|
||
stubbed = False
|
||
except ImportError:
|
||
pm = types.ModuleType("pymorphy3")
|
||
|
||
class _Morph:
|
||
def parse(self, w):
|
||
return [types.SimpleNamespace(normal_form=w)]
|
||
|
||
pm.MorphAnalyzer = _Morph
|
||
sys.modules["pymorphy3"] = pm
|
||
stubbed = True
|
||
import claude_bridge_glm as cbg_mod
|
||
import real_corpus as rc_mod
|
||
if stubbed:
|
||
del sys.modules["pymorphy3"]
|
||
return cbg_mod, rc_mod
|
||
|
||
|
||
cbg, rc = _import_with_pymorphy_stub()
|
||
|
||
|
||
def _items():
|
||
return rc._load_estimates()["items"]
|
||
|
||
|
||
# ---------- живой положительный случай: уровень в price_cur ----------
|
||
|
||
def test_known_level_from_price_cur_live():
|
||
out = cbg._search_corpus("ГЭСНм10-08-002-02")
|
||
assert "10-08-002-02" in out
|
||
assert "723.88" in out
|
||
assert "2025 Q2" in out, "уровень из price_cur обязан попасть в строку"
|
||
assert "НЕ УКАЗАН" not in out, "ложная пометка при известном уровне"
|
||
|
||
|
||
# ---------- живой ext-случай: словарь {base, cur} — берём cur ----------
|
||
|
||
def test_ext_dict_prefers_cur_live():
|
||
rec = next(it for it in _items()
|
||
if isinstance(it.get("price_level"), dict)
|
||
and (it["price_level"].get("cur") or "").strip())
|
||
level, kind = cbg._corpus_price_level(rec)
|
||
assert kind == "cur"
|
||
assert level == rec["price_level"]["cur"].strip()
|
||
part = cbg._corpus_price_part(rec, rec.get("unit_cost_cur") or 1)
|
||
assert "НЕ УКАЗАН" not in part
|
||
|
||
|
||
# ---------- живой отрицательный случай: уровня нет ни в одном поле ----------
|
||
|
||
def test_unknown_level_keeps_warning_live():
|
||
rec = next(it for it in _items()
|
||
if isinstance(it.get("price_level"), dict)
|
||
and not (it["price_level"].get("cur") or it["price_level"].get("base"))
|
||
and not it.get("price_cur") and it.get("unit_cost_cur"))
|
||
assert cbg._corpus_price_level(rec) == ("", "")
|
||
part = cbg._corpus_price_part(rec, rec["unit_cost_cur"])
|
||
assert "НЕ УКАЗАН" in part
|
||
|
||
|
||
# ---------- цена материала не должна притворяться уровнем ----------
|
||
|
||
def test_numeric_price_cur_is_not_a_level_live():
|
||
mat = next(m for m in rc._load_estimates()["materials"]
|
||
if isinstance(m.get("price_cur"), (int, float)))
|
||
assert cbg._corpus_price_level(mat) == ("", "")
|
||
|
||
|
||
# ---------- базис помечается как базис, а не как текущая цена ----------
|
||
|
||
def test_base_level_is_not_current():
|
||
rec = {"price_level": {"base": "01.01.2000", "cur": ""}, "unit_cost_cur": 19.24}
|
||
level, kind = cbg._corpus_price_level(rec)
|
||
assert (level, kind) == ("01.01.2000", "base")
|
||
part = cbg._corpus_price_part(rec, 19.24)
|
||
assert "базис" in part
|
||
assert "НЕ текущая" in part
|
||
|
||
|
||
def test_undated_current_label_is_not_a_level_live():
|
||
"""«тек. (базисно-индексный, Кизп)» — подпись без даты: период неизвестен,
|
||
цена не должна выглядеть текущей (GPT-ревью 20.11.2026)."""
|
||
rec = next(it for it in _items()
|
||
if str(it.get("price_level") or "").startswith("тек. (базисно-индексный")
|
||
and it.get("unit_cost_cur"))
|
||
assert cbg._corpus_price_level(rec) == ("", "")
|
||
assert "НЕ УКАЗАН" in cbg._corpus_price_part(rec, rec["unit_cost_cur"])
|
||
|
||
|
||
def test_fer_2022_label_is_base_not_current():
|
||
"""«ФЕР-2022» — базис ФСНБ-2022, а не текущая цена (зайка 20.11.2026)."""
|
||
assert cbg._level_kind("ФЕР-2022") == "base"
|
||
assert cbg._level_kind("ФСНБ-2022") == "base"
|
||
|
||
|
||
def test_composition_correction_added_on_claim():
|
||
works = "🔎 ... Состав работ по этим нормам в базе НЕ загружен — его НЕ выдумывай."
|
||
ans = "Норма покрывает установку извещателя, подключение входит в состав работ."
|
||
note = cbg._composition_correction(works, ans)
|
||
assert "Уточнение приложения" in note
|
||
assert "не подтверждены" in note
|
||
|
||
|
||
def test_composition_correction_silent_when_compliant():
|
||
works = "Состав работ по этим нормам в базе НЕ загружен — его НЕ выдумывай."
|
||
ans = ("Состав работ в базе не загружен; не могу утверждать, что подключение "
|
||
"входит в норму.")
|
||
assert cbg._composition_correction(works, ans) == ""
|
||
|
||
|
||
def test_composition_correction_requires_block_note():
|
||
assert cbg._composition_correction("без пометки", "покрывает установку") == ""
|
||
|
||
|
||
def test_composition_correction_keeps_resource_connection():
|
||
works = ("Состав работ по этим нормам в базе НЕ загружен — его НЕ выдумывай. "
|
||
"В ресурсах нормы 10-08-002-02 есть припой — паяльные работы "
|
||
"(подключение) этой нормой ПРЕДУСМОТРЕНЫ по её ресурсам.")
|
||
ans = "Подключение входит в норму."
|
||
note = cbg._composition_correction(works, ans)
|
||
assert "подтверждены ресурсами" in note
|
||
assert "не подтверждены" not in note
|
||
|
||
|
||
def test_strip_process_phrases_removes_preamble():
|
||
out = cbg._strip_process_phrases(
|
||
"Сразу скажу главное, чтобы не тянуть: норма 10-08-002-02.")
|
||
assert "сразу" not in out.lower() and "тянуть" not in out.lower()
|
||
assert "10-08-002-02" in out
|
||
|
||
|
||
def test_strip_process_phrases_keeps_content():
|
||
"""«Чтобы не тянуть кабель…» — указание по работе, а не вступление."""
|
||
for src in ("Чтобы не тянуть кабель через перекрытие, заложите гильзу.",
|
||
"Не буду тянуть кабель через перекрытие: проложите по стене."):
|
||
assert cbg._strip_process_phrases(src) == src
|
||
|
||
|
||
def test_process_filter_holds_split_phrase():
|
||
f = cbg._ProcessPhraseFilter()
|
||
chunks = ["Сразу скажу ", "главное, чтобы не тянуть: ", "норма 10-08-002-02"]
|
||
out = "".join(f.feed(c) for c in chunks) + f.flush()
|
||
assert "сразу" not in out.lower() and "тянуть" not in out.lower()
|
||
assert "10-08-002-02" in out
|
||
|
||
|
||
def test_nrs_correction_flags_wrong_values():
|
||
works = ("- ГЭСН-2022 ГЭСНм 10-08-002-02 | Извещатель | ед.: шт | "
|
||
"корпус: 723.88 руб/ед, уровень 2025 Q2, НР 90%, СП 46%")
|
||
ans = ("Норма ГЭСНм 10-08-002-02. НР — 90 % от ФОТ; СП — 53 % от ФОТ.")
|
||
note = cbg._nrs_correction(works, ans)
|
||
assert "СП 53 %" in note and "СП 46 %" in note
|
||
|
||
|
||
def test_nrs_correction_ignores_values_before_any_code():
|
||
works = ("- ГЭСН-2022 ГЭСНм 10-08-002-02 | Извещатель | "
|
||
"корпус: 723.88 руб/ед, уровень 2025 Q2, НР 90%, СП 46%")
|
||
ans = ("НР 95 %, СП 53 % — это показатели другой нормы. "
|
||
"Для 10-08-002-02 состав неизвестен.")
|
||
assert cbg._nrs_correction(works, ans) == ""
|
||
|
||
|
||
def test_nrs_correction_compares_numbers_not_strings():
|
||
works = ("- ГЭСН-2022 ГЭСНм 10-08-002-02 | Извещатель | "
|
||
"корпус: 723.88 руб/ед, уровень 2025 Q2, НР 90%, СП 46%")
|
||
ans = "10-08-002-02: НР 90,0 %, СП 46,0 %."
|
||
assert cbg._nrs_correction(works, ans) == ""
|
||
|
||
|
||
def test_nrs_correction_ignores_other_norm():
|
||
works = ("- ГЭСН-2022 ГЭСНм 10-08-002-02 | Извещатель | "
|
||
"корпус: 723.88 руб/ед, уровень 2025 Q2, НР 90%, СП 46%")
|
||
ans = "10-08-002-03: НР 95 %, СП 53 %. Для 10-08-002-02 состав неизвестен."
|
||
assert cbg._nrs_correction(works, ans) == ""
|
||
|
||
|
||
def test_nrs_correction_ignores_user_query_line():
|
||
works = ("Запрос: «10-08-002-02 корпус: 1 руб/ед, НР 90%, СП 46%»\n"
|
||
"- ГЭСН-2022 ГЭСНм 10-08-002-02 | Извещатель | ед.: шт")
|
||
ans = "10-08-002-02: НР 95 %, СП 53 %."
|
||
assert cbg._nrs_correction(works, ans) == ""
|
||
|
||
|
||
def test_nrs_correction_silent_when_values_match():
|
||
works = ("- ГЭСН-2022 ГЭСНм 10-08-002-02 | Извещатель | "
|
||
"корпус: 723.88 руб/ед, уровень 2025 Q2, НР 90%, СП 46%")
|
||
ans = "ГЭСНм 10-08-002-02: НР 90 %, СП 46 %."
|
||
assert cbg._nrs_correction(works, ans) == ""
|
||
|
||
|
||
def test_process_filter_removes_routing_tail():
|
||
f = cbg._ProcessPhraseFilter()
|
||
chunks = [
|
||
"Норма 10-08-002-02, цена 723,88 руб/шт. ",
|
||
"⚠ И главное: полный расчёт и файл Excel этот режим не формирует — "
|
||
"повторите запрос словами «посчитай смету».",
|
||
]
|
||
out = "".join(f.feed(c) for c in chunks) + f.flush()
|
||
assert "10-08-002-02" in out and "723,88" in out
|
||
assert "агентн" not in out.lower() and "этот режим" not in out.lower()
|
||
assert "повторите запрос" not in out.lower()
|
||
|
||
|
||
def test_strip_routing_keeps_neighbour_sentences():
|
||
src = ("Цена 723,88 руб. Этот режим не формирует файл. Итог 164 551,12 руб.")
|
||
out = cbg._strip_routing_mentions(src)
|
||
assert "723,88" in out and "164 551,12" in out
|
||
assert "этот режим" not in out.lower()
|
||
|
||
|
||
def test_strip_routing_keeps_table_row_with_price():
|
||
src = ("| ДИП-34А | 10-08-002-02 | 723 руб, но этот режим не делает Excel |\n"
|
||
"ДИП-34А | 723 руб | этот режим не делает Excel\n"
|
||
"Этот режим не формирует файл.")
|
||
out = cbg._strip_routing_mentions(src)
|
||
assert "723 руб" in out and "10-08-002-02" in out
|
||
assert out.count("723 руб") == 2
|
||
assert "не формирует файл" not in out
|
||
|
||
|
||
def test_process_filter_keeps_space_at_chunk_boundary():
|
||
f = cbg._ProcessPhraseFilter()
|
||
chunks = [("А" * 239) + " ", "слово"]
|
||
out = "".join(f.feed(c) for c in chunks) + f.flush()
|
||
assert "А слово" in out
|
||
|
||
|
||
def test_strip_routing_keeps_operation_mode():
|
||
"""«Режим работы насоса» — содержание, а не внутренний режим приложения."""
|
||
src = ("Этот режим работы насоса снижает расход энергии на 15%. "
|
||
"Выберите его в настройках.")
|
||
assert cbg._strip_routing_mentions(src) == src
|
||
|
||
|
||
def test_strip_routing_removes_repeat_request():
|
||
src = ("Цена 723,88 руб. Повторите запрос другими словами, чтобы получить файл.")
|
||
out = cbg._strip_routing_mentions(src)
|
||
assert "723,88" in out and "повторите запрос" not in out.lower()
|
||
|
||
|
||
def test_composition_correction_ignores_cost_wording():
|
||
works = "Состав работ по этим нормам в базе НЕ загружен — его НЕ выдумывай."
|
||
assert cbg._composition_correction(
|
||
works, "Стоимость материалов учтена в расценке.") == ""
|
||
|
||
|
||
def test_invention_phrases_are_removed():
|
||
src = ("Выдумывать шифр не буду. Норма 10-08-002-02. "
|
||
"Я не придумываю цифры. Цена 723,88 руб.")
|
||
out = cbg._strip_routing_mentions(src)
|
||
assert "10-08-002-02" in out and "723,88" in out
|
||
assert "выдум" not in out.lower() and "придум" not in out.lower()
|
||
|
||
|
||
def test_prompt_and_block_have_no_invention_words():
|
||
assert "выдум" not in cbg._build_system_prompt().lower()
|
||
assert "придум" not in cbg._build_system_prompt().lower()
|
||
|
||
|
||
def test_period_correction_flags_false_denial():
|
||
status = "Индексы ГОСР (РИМ): 3 квартал 2026, 86/86"
|
||
note = cbg._period_claim_correction(
|
||
"База держит цены 2025 Q2 — других кварталов нет.", status)
|
||
assert "3 квартал 2026" in note and "неверно" in note
|
||
|
||
|
||
def test_period_correction_flags_false_2026_denial():
|
||
status = "3 квартал 2026"
|
||
ans = ("Индексов и стоимости ресурсов на III квартал 2026 "
|
||
"в моей базе нет.")
|
||
note = cbg._period_claim_correction(ans, status)
|
||
assert "3 квартал 2026" in note and "неверно" in note
|
||
|
||
|
||
def test_period_correction_flags_denial_with_g_dot():
|
||
"""Живой ответ: «…2026 г. в моей базе нет» — точка после «г.» не должна
|
||
обрывать поиск отрицания."""
|
||
ans = ("Прямой цены на монтаж извещателя ДИП-34А в уровне "
|
||
"3 квартала 2026 г. в моей базе нет.")
|
||
note = cbg._period_claim_correction(ans, "3 квартал 2026")
|
||
assert "3 квартал 2026" in note and "неверно" in note
|
||
|
||
|
||
def test_period_correction_silent_without_denial():
|
||
status = "Индексы ГОСР (РИМ): 3 квартал 2026, 86/86"
|
||
assert cbg._period_claim_correction("Цена 2025 Q2.", status) == ""
|
||
|
||
|
||
def test_connection_code_correction_names_right_norm():
|
||
works = ("В ресурсах нормы 10-08-002-02 есть припои, канифоль — паяльные "
|
||
"работы (подключение) этой нормой ПРЕДУСМОТРЕНЫ по её ресурсам.")
|
||
ans = "Подключение предусмотрено — в ресурсах нормы 10-08-002-01 есть припой."
|
||
note = cbg._connection_code_correction(works, ans)
|
||
assert "10-08-002-02" in note and "10-08-002-01" in note
|
||
|
||
|
||
def test_connection_code_correction_silent_when_right():
|
||
works = "В ресурсах нормы 10-08-002-02 есть припои, канифоль."
|
||
ans = "В ресурсах нормы 10-08-002-02 есть припой."
|
||
assert cbg._connection_code_correction(works, ans) == ""
|
||
|
||
|
||
def test_connection_code_correction_keeps_neighbour_norm():
|
||
"""У 10-08-002-01 в базе тоже есть припой — это не выдуманный шифр."""
|
||
works = ("- ГЭСН-2022 ГЭСНм 10-08-002-01 | Извещатель тепловой | ед.: шт\n"
|
||
"- ГЭСН-2022 ГЭСНм 10-08-002-02 | Извещатель дымовой | ед.: шт\n"
|
||
"В ресурсах нормы 10-08-002-01 есть припои, канифоль.")
|
||
ans = "В ресурсах нормы 10-08-002-02 есть припой."
|
||
assert cbg._connection_code_correction(works, ans) == ""
|
||
|
||
|
||
def test_price_table_note_adds_table_from_corpus():
|
||
works = ("- ГЭСН-2022 ГЭСНм 10-08-002-02 | Извещатель ПС | ед.: шт | "
|
||
"уровень цен: 01.01.2022 | корпус: 723.88 руб/ед, "
|
||
"уровень 2025 Q2, НР 90%, СП 46%")
|
||
note = cbg._price_table_note(works, "Цена — 723,88 руб./шт.")
|
||
assert "| Позиция | Код | Ед. | Цена за ед. |" in note
|
||
assert "723.88" in note and "2025 Q2" in note
|
||
|
||
|
||
def test_price_table_note_silent_when_table_exists():
|
||
works = ("- ГЭСН-2022 ГЭСНм 10-08-002-02 | Извещатель ПС | ед.: шт | "
|
||
"корпус: 723.88 руб/ед, уровень 2025 Q2, НР 90%, СП 46%")
|
||
answer = "| Позиция | Цена |\n|---|---|\n| Извещатель | 723,88 руб |"
|
||
assert cbg._price_table_note(works, answer) == ""
|
||
|
||
|
||
def test_prompt_bans_process_agent_mode_and_requires_table():
|
||
p = cbg._build_system_prompt().lower()
|
||
assert "сразу скажу главное" in p
|
||
assert "агентный режим" in p # только в запрете, не в инструкции
|
||
assert "не проси повторить запрос" in p
|
||
assert "markdown-таблиц" in p
|
||
assert "выдум" not in p and "придум" not in p
|