release: Themiz на Gitea
This commit is contained in:
Regular → Executable
+206
-20
@@ -28,12 +28,15 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import datetime
|
||||
import glob
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
@@ -43,6 +46,7 @@ import case_paths as cp # noqa: E402
|
||||
POLICY_NAME = "quality_gate.json"
|
||||
SUPPRESSIONS_NAME = "quality_gate.suppressions.jsonl"
|
||||
PACKAGE_REGISTRY_NAME = "sostav_paketa.md"
|
||||
SOURCE_MANIFEST_NAME = "quality_gate.sources.json"
|
||||
PACKAGE_DRAFT_RE = re.compile(r"^\d{2}_.+\.md$")
|
||||
POLICY_KINDS = frozenset({"remark", "prohibition"})
|
||||
POLICY_EXPECT = frozenset({"present", "absent"})
|
||||
@@ -52,6 +56,20 @@ def policy_path(case: str) -> str:
|
||||
return str(cp.working(case) / POLICY_NAME)
|
||||
|
||||
|
||||
def ensure_policy(case: str) -> str:
|
||||
"""Создать пустой файл решений, не трогая существующий путь любого вида."""
|
||||
path = policy_path(case)
|
||||
if os.path.lexists(path):
|
||||
return path
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
try:
|
||||
with open(path, "x", encoding="utf-8") as target:
|
||||
target.write('{"version":1,"rules":[]}\n')
|
||||
except FileExistsError:
|
||||
pass
|
||||
return path
|
||||
|
||||
|
||||
def suppressions_path(case: str) -> str:
|
||||
return str(cp.working(case) / SUPPRESSIONS_NAME)
|
||||
|
||||
@@ -310,17 +328,39 @@ def page_text_bad(text: str) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def _ocr_source_kind(ocr_dir: str, manifest: dict | None) -> str | None:
|
||||
"""Определить image/pdf по исходнику, а не по имени каталога рендера."""
|
||||
from markdown_extract import IMAGE, ext_of, sha256_of
|
||||
|
||||
if ext_of(Path(ocr_dir).name) == "pdf":
|
||||
return "pdf"
|
||||
|
||||
digest = (manifest or {}).get("source_sha256")
|
||||
if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-fA-F]{64}", digest):
|
||||
return None
|
||||
|
||||
cases = Path(__file__).resolve().parents[1] / "cases"
|
||||
for source in cases.glob("**/00_intake/**/*") if cases.is_dir() else ():
|
||||
if not source.is_file() or ext_of(source.name) not in IMAGE | {"pdf"}:
|
||||
continue
|
||||
try:
|
||||
matches = sha256_of(source).lower() == digest.lower()
|
||||
except OSError:
|
||||
continue
|
||||
if matches:
|
||||
return "image" if ext_of(source.name) in IMAGE else "pdf"
|
||||
return None
|
||||
|
||||
|
||||
def check_ocr(ocr_dir: str) -> list[str]:
|
||||
"""Каждая отрисованная страница дошла до текста; таблицы не потеряны."""
|
||||
problems: list[str] = []
|
||||
pngs = sorted(glob.glob(os.path.join(ocr_dir, "page_*.png")))
|
||||
if not pngs:
|
||||
return [f"{ocr_dir}: нет отрисованных страниц (page_*.png) — OCR не выполнялся"]
|
||||
|
||||
man_path = os.path.join(ocr_dir, "manifest.json")
|
||||
man = None
|
||||
if os.path.isfile(man_path):
|
||||
try:
|
||||
man = json.load(open(man_path, encoding="utf-8"))
|
||||
man = json.loads(Path(man_path).read_text(encoding="utf-8"))
|
||||
if not man.get("complete", True):
|
||||
problems.append(
|
||||
f"МАНИФЕСТ НЕПОЛОН: missing={man.get('missing')}, "
|
||||
@@ -328,22 +368,37 @@ def check_ocr(ocr_dir: str) -> list[str]:
|
||||
except (OSError, ValueError) as e:
|
||||
problems.append(f"манифест не читается ({e}) — полнота OCR не подтверждена")
|
||||
|
||||
# Для одиночной картинки исходник и есть растр: ocr_image пишет только
|
||||
# page_001.txt + manifest.json. Скан-PDF по-прежнему обязан иметь page_*.png.
|
||||
# --render-dir и кеш {sha}_ocr не хранят расширение, поэтому вид исходника
|
||||
# подтверждаем по source_sha256 манифеста. Неопознанный исходник fail-closed.
|
||||
if not pngs:
|
||||
image_only = _ocr_source_kind(ocr_dir, man) == "image"
|
||||
pages = (man or {}).get("pages") or {}
|
||||
if not (image_only and (man or {}).get("complete") is True
|
||||
and int((man or {}).get("total_pages") or 0) == 1
|
||||
and pages.get("1") in {"ocr", "ocr_empty"}):
|
||||
problems.append(
|
||||
f"{ocr_dir}: нет отрисованных страниц (page_*.png) — OCR не выполнялся")
|
||||
return problems
|
||||
pngs = [os.path.join(ocr_dir, "page_001.txt")]
|
||||
|
||||
from table_guard import grid_signals, text_has_structure
|
||||
lost, empty, faint_lost = [], [], []
|
||||
for png in pngs:
|
||||
txt_path = os.path.splitext(png)[0] + ".txt"
|
||||
txt_path = png if png.endswith(".txt") else os.path.splitext(png)[0] + ".txt"
|
||||
page = os.path.basename(png)
|
||||
if not os.path.isfile(txt_path):
|
||||
problems.append(f"{page}: страница отрисована, но НЕ распознана (нет .txt)")
|
||||
continue
|
||||
txt = open(txt_path, encoding="utf-8", errors="ignore").read()
|
||||
txt = Path(txt_path).read_text(encoding="utf-8", errors="ignore")
|
||||
if not txt.strip():
|
||||
empty.append(page)
|
||||
continue
|
||||
bad = page_text_bad(txt)
|
||||
if bad:
|
||||
problems.append(f"{page}: {bad}")
|
||||
g = grid_signals(png)
|
||||
g = grid_signals(png) if png.endswith(".png") else {"grid": False, "faint": False}
|
||||
if g["grid"] and not text_has_structure(txt):
|
||||
# Бледная сетка больше не глушит сигнал целиком: table_guard.py для той же
|
||||
# страницы дает TABLE_STRUCTURE_LOST, и два инструмента проекта расходились
|
||||
@@ -379,6 +434,47 @@ def is_practice_source(path: str) -> bool:
|
||||
return os.path.basename(path) in PRACTICE_SOURCES
|
||||
|
||||
|
||||
# Даты черновика сверяются с источниками фактов целиком (T446, 12.10.2026). Раньше «01.02» и «2026» вырезались
|
||||
# из сверки, и дата, выдуманная для доверителя, проходила ворота. Запись даты приводится к Д.М.ГГГГ: «12 октября
|
||||
# 2026», «12.10.26» и «12.10.2026» — одна дата. Без находки остаются дата документа (сегодня), дата в реквизитах
|
||||
# акта или нормы («Пленума … от 23.06.2015 № 25», «ред. от …») и дата, которая стоит в практике.
|
||||
_MESYACY = ("января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября",
|
||||
"ноября", "декабря")
|
||||
_DATA_SLOVOM = re.compile(r"«?(\d{1,2})»?\s+(" + "|".join(_MESYACY) + r")\s+(\d{4})", re.I)
|
||||
_DATA = re.compile(r"(?<![\d.])(\d{1,2})\.(\d{1,2})\.(\d{4}|\d{2})(?!\d)")
|
||||
_AKT_DO = re.compile(r"(?:\bред\.\s*|(?:пленум|постановлени|определени|решени|приговор|закон|кодекс|ФЗ|приказ|указ|"
|
||||
r"обзор|письм|распоряжени)\w*(?:(?!\bот\b)[^\n;]){0,120}?\b)от\s*$", re.I)
|
||||
_AKT_POSLE = re.compile(r"^\s*(?:г\.?\s*)?(?:по\s+делу\s*)?№")
|
||||
|
||||
|
||||
def _god(text: str) -> int:
|
||||
year = int(text)
|
||||
if len(text) == 2:
|
||||
year += 2000 if year <= datetime.date.today().year % 100 + 1 else 1900
|
||||
return year
|
||||
|
||||
|
||||
def daty_of(text: str) -> list[tuple[str, int, int]]:
|
||||
"""Даты текста: (Д.М.ГГГГ, начало, конец записи)."""
|
||||
out = [(f"{int(m[1])}.{_MESYACY.index(m[2].casefold()) + 1}.{m[3]}", m.start(), m.end())
|
||||
for m in _DATA_SLOVOM.finditer(text)]
|
||||
out += [(f"{int(m[1])}.{int(m[2])}.{_god(m[3])}", m.start(), m.end()) for m in _DATA.finditer(text)]
|
||||
return out
|
||||
|
||||
|
||||
def check_dates(text: str, facts_text: str, practice_text: str) -> list[str]:
|
||||
"""Даты черновика, которых нет в источниках фактов, кроме даты документа и реквизитов акта."""
|
||||
today = datetime.date.today()
|
||||
known = {d for d, _, _ in daty_of(facts_text) + daty_of(practice_text)} | {f"{today.day}.{today.month}.{today.year}"}
|
||||
bad = sorted({d for d, start, end in daty_of(text) if d not in known
|
||||
and not (_AKT_DO.search(text[max(0, start - 200):start])
|
||||
and (_AKT_POSLE.match(text[end:end + 30]) or re.search(r"ред\.\s*от\s*$", text[max(0, start - 20):start])))})
|
||||
if not bad:
|
||||
return []
|
||||
return [f"в черновике {len(bad)} дат, которых нет ни в одном источнике фактов: {', '.join(bad[:25])}"
|
||||
f"{'…' if len(bad) > 25 else ''} — подтвердить материалами дела или убрать"]
|
||||
|
||||
|
||||
def check_numbers(draft: str, sources: list[str], min_digits: int = 4) -> list[str]:
|
||||
"""Числа черновика обязаны быть в источниках ФАКТОВ дела, а не в практике."""
|
||||
from crosscheck_numbers import numbers_of
|
||||
@@ -387,36 +483,54 @@ def check_numbers(draft: str, sources: list[str], min_digits: int = 4) -> list[s
|
||||
text = stream.read()
|
||||
except OSError as exc:
|
||||
return [f"черновик не прочитан: {exc}"]
|
||||
in_draft = numbers_of(text, min_digits)
|
||||
facts = [s for s in sources if not is_practice_source(s)]
|
||||
practice = [s for s in sources if is_practice_source(s)]
|
||||
unreadable = []
|
||||
in_src = None
|
||||
facts_text = ""
|
||||
for s in facts:
|
||||
try:
|
||||
with open(s, encoding="utf-8", errors="ignore") as stream:
|
||||
n = numbers_of(stream.read(), min_digits)
|
||||
body = stream.read()
|
||||
facts_text += "\n" + body
|
||||
n = numbers_of(body, min_digits)
|
||||
except OSError as exc:
|
||||
unreadable.append(f"источник {os.path.basename(s)} не прочитан: {exc}")
|
||||
continue
|
||||
in_src = n if in_src is None else (in_src | n)
|
||||
in_practice = None
|
||||
practice_text = ""
|
||||
for s in practice:
|
||||
try:
|
||||
with open(s, encoding="utf-8", errors="ignore") as stream:
|
||||
n = numbers_of(stream.read(), min_digits)
|
||||
body = stream.read()
|
||||
except OSError as exc:
|
||||
unreadable.append(f"источник {os.path.basename(s)} не прочитан: {exc}")
|
||||
continue
|
||||
practice_text += "\n" + body
|
||||
n = numbers_of(body, min_digits)
|
||||
in_practice = n if in_practice is None else (in_practice | n)
|
||||
# Номер дела акта из практики («дело № 33-20261/2026») — реквизит акта, а не сумма: его держит verify_act,
|
||||
# акт вне списка ловит Кони. Номер, стоящий в практике целиком, из сверки чисел снимается (приемка
|
||||
# 10.10.2026: preflight красный на номере подтвержденного акта, правка Сперанского ушла на ложную находку).
|
||||
for delo in set(re.findall(r"(?<![\w/-])[А-ЯA-Z]?\d+(?:-[А-ЯA-Z]*\d+)+/\d{4}(?![\w/-])", text)):
|
||||
if re.search(rf"(?<![\w/-]){re.escape(delo)}(?![\w/-])", practice_text):
|
||||
text = re.sub(rf"(?<![\w/-]){re.escape(delo)}(?![\w/-])", " ", text)
|
||||
unreadable += check_dates(text, facts_text, practice_text)
|
||||
in_draft = numbers_of(text, min_digits)
|
||||
# Разность именно по НАБОРУ чисел, не по счетчикам: у Counter «-» вычитает
|
||||
# частоты, и реквизит, названный в договоре трижды, а в источнике однажды,
|
||||
# оставался в остатке как «неподтвержденный». Найдено 20.08.2026 на договоре,
|
||||
# где ИНН и счета законно повторяются в преамбуле, приложениях и реквизитах.
|
||||
known = set(in_src or ())
|
||||
# Паспорт: в документе серия и номер раздельно, в карте дела одним числом
|
||||
# (приемка 10.10.2026, preflight красный на верно оформленном паспорте ответчика).
|
||||
for seria, nomer in re.findall(r"[Сс]ери[яиюей]\s+(\d[\d ]*\d)\s*№\s*(\d+)", text):
|
||||
if re.sub(r"\D", "", seria) + nomer in known:
|
||||
known |= set(numbers_of(seria, min_digits)) | set(numbers_of(nomer, min_digits))
|
||||
orphan = type(in_draft)({t: c for t, c in in_draft.items() if t not in known})
|
||||
# Даты и годы выкидываем: «01.02» и «2026» из даты документа законно отсутствуют
|
||||
# в карте дела, а в отчете они забивают собой реальные суммы. Даты — зона Кони.
|
||||
# Части дат («01.02», «2026») из сверки чисел выкидываем: даты целиком сверяет check_dates выше,
|
||||
# а осколки в отчете забивали бы собой реальные суммы.
|
||||
for tok in [t for t in orphan
|
||||
if re.fullmatch(r"\d{2}\.\d{2}", t) or re.fullmatch(r"(19|20)\d{2}", t)]:
|
||||
del orphan[tok]
|
||||
@@ -453,6 +567,17 @@ def check_requisites(path: str, bik: str | None) -> list[str]:
|
||||
EXTRACT_CACHE = os.path.expanduser("~/.cache/legal_extract")
|
||||
|
||||
|
||||
def case_requisite_sources(case: str) -> list[str]:
|
||||
"""Материалы 00_intake, для которых роутер создает кеш реквизитов."""
|
||||
from markdown_extract import IMAGE, OFFICE, ext_of
|
||||
|
||||
kinds = OFFICE | IMAGE | {"pdf", "doc", "xls", "ppt"}
|
||||
intake = os.path.join(case, cp.INTAKE)
|
||||
return [path for path in sorted(glob.glob(os.path.join(intake, "**", "*"),
|
||||
recursive=True))
|
||||
if os.path.isfile(path) and ext_of(path) in kinds]
|
||||
|
||||
|
||||
def case_requisite_files(case: str, cache_dir: str = EXTRACT_CACHE) -> list[str]:
|
||||
"""Файлы <sha>.requisites.json, относящиеся к материалам ЭТОГО дела.
|
||||
|
||||
@@ -472,6 +597,10 @@ def case_requisite_files(case: str, cache_dir: str = EXTRACT_CACHE) -> list[str]
|
||||
from markdown_extract import IMAGE, OFFICE, ext_of, sha_of
|
||||
|
||||
kinds = OFFICE | IMAGE | {"pdf", "doc", "xls", "ppt"}
|
||||
cache_dirs = tuple(dict.fromkeys((
|
||||
cache_dir,
|
||||
os.path.join(os.environ.get("TMPDIR") or tempfile.gettempdir(), "legal_extract"),
|
||||
)))
|
||||
out: list[str] = []
|
||||
for root, dirs, files in os.walk(case):
|
||||
dirs[:] = [d for d in dirs if d not in ("_baselines", "__pycache__")]
|
||||
@@ -480,11 +609,17 @@ def case_requisite_files(case: str, cache_dir: str = EXTRACT_CACHE) -> list[str]
|
||||
if ext_of(path) not in kinds:
|
||||
continue
|
||||
try:
|
||||
req = os.path.join(cache_dir, f"{sha_of(path)}.requisites.json")
|
||||
digest = sha_of(path)
|
||||
except OSError:
|
||||
continue
|
||||
if os.path.isfile(req) and req not in out:
|
||||
out.append(req)
|
||||
# первый найденный сайдкар на sha: копия того же файла в кеше $TMPDIR не меняет отпечаток preflight,
|
||||
# иначе допуск зависит от окружения (приемка 10.10.2026 20:45: прогон зеленый, проверка из песочницы красная)
|
||||
for cache in cache_dirs:
|
||||
req = os.path.join(cache, f"{digest}.requisites.json")
|
||||
if os.path.isfile(req):
|
||||
if req not in out:
|
||||
out.append(req)
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
@@ -503,11 +638,45 @@ def case_paths(case: str) -> dict:
|
||||
sources = [p for p in (os.path.join(ctx, n) for n in
|
||||
("knowledge-map.md", "positions.md", "practice.md"))
|
||||
if os.path.isfile(p)]
|
||||
sources += sorted(glob.glob(os.path.join(ctx, "_working", "*.md")))
|
||||
return {"drafts": drafts, "sources": sources,
|
||||
manifest = os.path.join(ctx, "_working", SOURCE_MANIFEST_NAME)
|
||||
source_manifest = manifest if os.path.isfile(manifest) else None
|
||||
if os.path.isfile(manifest):
|
||||
try:
|
||||
data = json.load(open(manifest, encoding="utf-8"))
|
||||
declared = data.get("sources", []) if isinstance(data, dict) else []
|
||||
# Прогон themiz-next объявляет первичку, карточку, ответы владельца, приборы и поручение и ставит
|
||||
# «bez_pereskaza»: карта и позиция — пересказ моделей, число, помеченное в карте ОСПОРЕНО,
|
||||
# не подтверждает то же число в черновике (T452).
|
||||
if isinstance(data, dict) and data.get("bez_pereskaza") is True:
|
||||
sources = [p for p in sources
|
||||
if os.path.basename(p) not in ("knowledge-map.md", "positions.md")]
|
||||
for item in declared:
|
||||
path = os.path.realpath(os.path.join(case, os.fspath(item)))
|
||||
if (path.startswith(os.path.realpath(case) + os.sep) and
|
||||
os.path.isfile(path) and is_factual_source(path)):
|
||||
sources.append(path)
|
||||
except (OSError, ValueError, TypeError):
|
||||
pass
|
||||
return {"drafts": drafts, "sources": sources, "source_manifest": source_manifest,
|
||||
"requisites": case_requisite_files(case)}
|
||||
|
||||
|
||||
_SERVICE_SOURCE_RE = re.compile(
|
||||
r"(?:^|[-_])(review(?:er|_log)?|handoff|preflight|quality[_-]?gate|verdict|status)"
|
||||
r"(?:[-_.]|$)|(?:^|[-_])report(?:[-_.]|$)", re.I)
|
||||
|
||||
|
||||
def is_factual_source(path: str) -> bool:
|
||||
"""Служебные отчеты не становятся источниками чисел для quality_gate.
|
||||
|
||||
Их можно хранить и читать как журнал, но изменение отчета не должно
|
||||
легализовать число в документе и не должно отзывать preflight. Настоящие
|
||||
карты, позиции, практика, первичка и реквизиты остаются зависимостями.
|
||||
"""
|
||||
name = os.path.basename(os.fspath(path))
|
||||
return not bool(_SERVICE_SOURCE_RE.search(name))
|
||||
|
||||
|
||||
def check_package_registry(case: str, drafts: list[str] | None = None) -> list[str]:
|
||||
"""Сверить имена черновиков с подтвержденным владельцем составом пакета."""
|
||||
registry = cp.working(case) / PACKAGE_REGISTRY_NAME
|
||||
@@ -556,6 +725,11 @@ def print_rules(json_mode: bool = False) -> int:
|
||||
"format": {"finding_id": "16 hex", "reason": "почему неприменимо"},
|
||||
"limit": "подавляются только remark; prohibition не подавляется",
|
||||
},
|
||||
"sources": {
|
||||
"path": ".agent/context/_working/quality_gate.sources.json",
|
||||
"format": {"sources": [".agent/context/knowledge-map.md"]},
|
||||
"mode": "явный список фактических источников; остальные рабочие отчеты не индексируются",
|
||||
},
|
||||
}
|
||||
if json_mode:
|
||||
print(json.dumps(schema, ensure_ascii=False, indent=2))
|
||||
@@ -597,6 +771,12 @@ def main() -> int:
|
||||
|
||||
report: list[tuple[str, str, list[str]]] = []
|
||||
docs: list[str] = []
|
||||
if args.case:
|
||||
from koiz_repair import CASE_WORK_OK, gate
|
||||
repair = gate(Path(args.case).resolve().parents[2], Path(__file__).resolve().parents[1])
|
||||
if repair["status"] not in CASE_WORK_OK:
|
||||
print(json.dumps({"status": "blocked", "koiz": repair}, ensure_ascii=False))
|
||||
return 2
|
||||
paths = case_paths(args.case) if args.case else None
|
||||
if args.ocr:
|
||||
report.append(("ocr", f"OCR {args.ocr}", check_ocr(args.ocr)))
|
||||
@@ -644,8 +824,7 @@ def main() -> int:
|
||||
found += check_requisites(r, args.bik)
|
||||
report.append(("case.requisites",
|
||||
f"реквизиты материалов дела ({len(reqs)} файлов)", found))
|
||||
elif any(os.path.isfile(path) for path in glob.glob(
|
||||
os.path.join(args.case, "00_intake", "**", "*"), recursive=True)):
|
||||
elif case_requisite_sources(args.case):
|
||||
report.append(("case.requisites", f"реквизиты дела {args.case}",
|
||||
["в кеше роутера нет ни одного <sha>.requisites.json для "
|
||||
"материалов дела — материалы не прогнаны через "
|
||||
@@ -711,8 +890,13 @@ def selftest() -> int:
|
||||
draft = os.path.join(tmp, "draft.md")
|
||||
src = os.path.join(tmp, "map.md")
|
||||
open(draft, "w", encoding="utf-8").write("Взыскать 1250000 руб. по договору 4412 от 01.02.2026.")
|
||||
open(src, "w", encoding="utf-8").write("Договор 4412. Сумма 1250000 руб.")
|
||||
open(src, "w", encoding="utf-8").write("Договор 4412 от 1 февраля 2026 г. Сумма 1250000 руб.")
|
||||
clean = check_numbers(draft, [src])
|
||||
# дата черновика, которой нет в источнике, — находка (T446); дата акта с номером — нет
|
||||
draft_date = os.path.join(tmp, "draft_date.md")
|
||||
open(draft_date, "w", encoding="utf-8").write(
|
||||
"По договору 4412 от 03.02.2026; постановление Пленума от 23.06.2015 № 25.")
|
||||
dated = check_numbers(draft_date, [src])
|
||||
|
||||
# Фикстуры для разделения источников: одно и то же число 7654321 лежит либо
|
||||
# в карте дела (факт доверителя), либо только в practice.md (чужое дело).
|
||||
@@ -805,6 +989,8 @@ def selftest() -> int:
|
||||
|
||||
checks = [
|
||||
("совпавшие числа замечаний не дают", clean == []),
|
||||
("дата не из источника — находка, дата акта — нет",
|
||||
len(dated) == 1 and "3.2.2026" in dated[0] and "23.6.2015" not in dated[0]),
|
||||
("число из воздуха ловится", len(dirty) == 1 and "9999999" in dirty[0]),
|
||||
("реквизит, повторенный в документе, подтвержденным и остается", repeated == []),
|
||||
# Практика — не источник фактов дела. Число из ЧУЖОГО судебного акта
|
||||
|
||||
Reference in New Issue
Block a user