89 lines
4.4 KiB
Python
89 lines
4.4 KiB
Python
"""Квитанция приемки (T450): по делу и виду документа печатает JSON-итог прогона. Конвейер не гонит.
|
||
|
||
Поля: docx (путь, имя, sha256), коды document_guard и verdict --check, токены и минуты последнего прогона.
|
||
Код 0 - DOCX в GOTOVO/ есть, не «_ЧЕРНОВИК», оба прибора вернули 0. Иначе 1 (причины в "problems").
|
||
Имена выдачи: «<вид>_ГОТОВ_К_ПОДАЧЕ.docx» (после T439) и «<вид>.docx»; «<вид>_ЧЕРНОВИК.docx» - код 1.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import hashlib
|
||
import json
|
||
import subprocess
|
||
import sys
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
|
||
import core
|
||
|
||
MD_SLACK = 60 # с: сборка копирует .md сразу после .docx, разница в секунды - не устаревание
|
||
SUFFIXES = ("_ГОТОВ_К_ПОДАЧЕ", "", "_ЧЕРНОВИК")
|
||
|
||
|
||
def _code(tool: str, args: list[str]) -> int:
|
||
return subprocess.run([*core.TOOLS[tool], *args], stdin=subprocess.DEVNULL, capture_output=True, cwd=core.ROOT).returncode
|
||
|
||
|
||
def _last_run(case: Path) -> dict:
|
||
"""Токены и минуты последнего прогона: tokens_total из state.json (иначе сумма событий), минуты - по ts событий."""
|
||
runs = sorted(path for path in (case / ".agent" / "next").glob("*/state.json"))
|
||
if not runs:
|
||
return {}
|
||
state_file = runs[-1]
|
||
state = json.loads(state_file.read_text(encoding="utf-8"))
|
||
events = []
|
||
log = state_file.with_name("events.jsonl")
|
||
if log.is_file():
|
||
events = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines() if line.strip()]
|
||
tokens = state.get("tokens_total")
|
||
if tokens is None:
|
||
tokens = sum(sum(event.get("tokens", {}).values()) for event in events)
|
||
stamps = [datetime.fromisoformat(event["ts"]) for event in events if "ts" in event]
|
||
minutes = round((max(stamps) - min(stamps)).total_seconds() / 60, 1) if stamps else None
|
||
return {"run": state_file.parent.name, "status": state.get("status"), "tokens": tokens, "minutes": minutes}
|
||
|
||
|
||
def receipt(case: Path, doc: str) -> tuple[dict, int]:
|
||
slug = core.slug(doc)
|
||
paths = core.contract(case, slug)
|
||
ready = paths["ready_docx"].parent
|
||
found = next(((ready / f"{slug}{suffix}.docx", suffix) for suffix in SUFFIXES if (ready / f"{slug}{suffix}.docx").is_file()), None)
|
||
out: dict = {"case": str(case), "doc": doc, "run": _last_run(case), "problems": []}
|
||
if found is None:
|
||
out["problems"].append(f"нет DOCX в {ready}")
|
||
return out, 1
|
||
docx, suffix = found
|
||
out["docx"] = {"path": str(docx), "sha256": hashlib.sha256(docx.read_bytes()).hexdigest()}
|
||
out["codes"] = {
|
||
"document_guard": _code("document_guard", [str(docx), "--md", str(paths["ready_md"])]),
|
||
"verdict_check": _code("verdict", ["--check", str(paths["draft_md"])]),
|
||
}
|
||
stamp = docx.stat().st_mtime
|
||
draft = ready / f"{slug}_ЧЕРНОВИК.docx"
|
||
if suffix != "_ЧЕРНОВИК" and draft.is_file() and draft.stat().st_mtime > stamp:
|
||
out["problems"].append("последняя выдача — черновик: «ЧЕРНОВИК» новее готового DOCX")
|
||
if suffix != "_ЧЕРНОВИК" and paths["ready_md"].is_file() and paths["ready_md"].stat().st_mtime > stamp + MD_SLACK:
|
||
out["problems"].append("устаревший DOCX: ready_md новее")
|
||
if suffix == "_ЧЕРНОВИК":
|
||
out["problems"].append("выдача помечена «ЧЕРНОВИК»: форма не принята или допрос открыт")
|
||
out["problems"] += [f"{name}: код {code}" for name, code in out["codes"].items() if code]
|
||
return out, 1 if out["problems"] else 0
|
||
|
||
|
||
def main(argv: list[str]) -> int:
|
||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||
parser.add_argument("case", type=Path)
|
||
parser.add_argument("--doc", required=True, help="вид документа, как в run.py --doc")
|
||
args = parser.parse_args(argv)
|
||
try:
|
||
out, code = receipt(args.case.resolve(), args.doc)
|
||
except core.Stop as error:
|
||
print(f"стоп: {error}", file=sys.stderr)
|
||
return 1
|
||
print(json.dumps(out, ensure_ascii=False, indent=2))
|
||
return code
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main(sys.argv[1:]))
|