perf: разбор YAML сценариев через libyaml

This commit is contained in:
gglamer 2026-09-26 19:27:52 +00:00
commit d26cf2365d
2 changed files with 9 additions and 2 deletions

View file

@ -22,6 +22,7 @@ from app.domain.events import Mood
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
LIBRARY = Path(__file__).resolve().parents[3] / "scenarios" / "pregenerated" LIBRARY = Path(__file__).resolve().parents[3] / "scenarios" / "pregenerated"
_Loader = getattr(yaml, "CSafeLoader", yaml.SafeLoader)
def table_path(scenario_id: str) -> Path: def table_path(scenario_id: str) -> Path:
@ -40,7 +41,9 @@ class TreeCaller:
""" """
def __init__(self, scenario_id: str) -> None: def __init__(self, scenario_id: str) -> None:
self._table = yaml.safe_load(table_path(scenario_id).read_text(encoding="utf-8")) or {} self._table = yaml.load(
table_path(scenario_id).read_text(encoding="utf-8"), Loader=_Loader
) or {}
self._fallback = TemplateCaller() self._fallback = TemplateCaller()
self._turn = 0 self._turn = 0
self.misses = 0 self.misses = 0

View file

@ -14,6 +14,10 @@ from app.domain import ekp
from app.domain.classifiers import DDS_BY_INCIDENT from app.domain.classifiers import DDS_BY_INCIDENT
from app.scenarios.schema import ChecklistItem, Scenario from app.scenarios.schema import ChecklistItem, Scenario
# Библиотека читается на каждом старте приложения, а в тестах — на каждый
# TestClient: чистый Python-парсер тратит на неё ~1.7 с, libyaml — ~0.2 с.
_Loader = getattr(yaml, "CSafeLoader", yaml.SafeLoader)
class ScenarioError(Exception): class ScenarioError(Exception):
"""Ошибка библиотеки. Текст пишется для методиста, не для программиста.""" """Ошибка библиотеки. Текст пишется для методиста, не для программиста."""
@ -21,7 +25,7 @@ class ScenarioError(Exception):
def _read_yaml(path: Path) -> dict: def _read_yaml(path: Path) -> dict:
try: try:
data = yaml.safe_load(path.read_text(encoding="utf-8")) data = yaml.load(path.read_text(encoding="utf-8"), Loader=_Loader)
except yaml.YAMLError as exc: except yaml.YAMLError as exc:
raise ScenarioError(f"{path.name}: битый YAML — {exc}") from exc raise ScenarioError(f"{path.name}: битый YAML — {exc}") from exc
if not isinstance(data, dict): if not isinstance(data, dict):