Spaces:
Sleeping

File size: 4,003 Bytes
4df9b63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import math

import numpy as np
import pytest
from pydantic import ValidationError

from decision_model.schemas import DecisionRequest
from decision_model.encoding import render_question, candidate_masks, mean_pool
from decision_model.prediction import assemble_answer


def request(kind="choice", criteria=None):
    q = {"type": kind, "instructions": "Яка відповідь?"}
    if criteria is not None:
        q["criteria"] = criteria
    return DecisionRequest.model_validate({"state": "Поверніть кошти", "questions": {"q": q}})


def test_schema_accepts_all_three_pdf_types():
    assert request("noul").questions["q"].type == "noul"
    assert request(criteria={"a": "Так", "b": "Ні"}).questions["q"].criteria["a"] == "Так"
    assert request("score", ["Спокій", "Гнів"]).questions["q"].criteria == ["Спокій", "Гнів"]


@pytest.mark.parametrize("patch", [
    {"state": "  "}, {"questions": {}}, {"model": "unknown"},
    {"questions": {" ": {"type": "noul", "instructions": "Q"}}},
    {"questions": {"q": {"type": "choice", "instructions": "Q", "criteria": {"a": "x"}}}},
    {"questions": {"q": {"type": "score", "instructions": "Q", "criteria": ["x", "x"]}}},
])
def test_schema_rejects_invalid_input(patch):
    body = {"state": "hello", "questions": {"q": {"type": "noul", "instructions": "Q"}}}
    with pytest.raises(ValidationError):
        DecisionRequest.model_validate({**body, **patch})


def test_serialization_uses_positions_and_never_class_ids():
    q = request(criteria={"secret-id": "Так", "another-id": "Ні"}).questions["q"]
    text, spans, ids = render_question("Так <|choice|> Так", q)
    assert "secret-id" not in text
    assert ids == ["secret-id", "another-id"]
    assert [text[a:b] for a, b in spans] == ["Так", "Ні"]
    assert spans[0][0] > text.index("Так")


def test_pooling_excludes_markers_padding_and_repeated_state_text():
    offsets = [(0, 0), (0, 3), (4, 7), (8, 11), (0, 0)]
    masks = candidate_masks(offsets, [(4, 7), (8, 11)])
    hidden = np.array([[999, 999], [888, 888], [2, 4], [6, 8], [777, 777]], dtype=float)
    np.testing.assert_allclose(mean_pool(hidden, masks), [[2, 4], [6, 8]])
    with pytest.raises(ValueError, match="токен"):
        candidate_masks(offsets, [(20, 25)])


def test_pdf_answers_are_probabilistic_and_score_is_expectation():
    q = request("noul").questions["q"]
    assert assemble_answer(q, [0.2, 0.8]).noul == pytest.approx(0.8)
    q = request(criteria={"b": "Рахунки", "t": "Технічні проблеми"}).questions["q"]
    answer = assemble_answer(q, [0.8, 0.2])
    assert answer.choice == "b" and answer.confidence == pytest.approx(0.8)
    q = request("score", ["Спокій", "Невдоволення", "Гнів"]).questions["q"]
    answer = assemble_answer(q, [0.07, 0.68, 0.25])
    assert answer.score == pytest.approx(1.18)
    assert answer.legend["2"] == "Гнів"
    assert math.isclose(sum(answer.probabilities.values()), 1)


@pytest.mark.parametrize("values", [[float("nan"), 0.5], [0.2, 0.2], [-0.1, 1.1]])
def test_invalid_probability_outputs_never_serialize(values):
    with pytest.raises(ValueError):
        assemble_answer(request("noul").questions["q"], values)


def test_unfinished_artifacts_are_rejected_before_loading_encoder(tmp_path, monkeypatch):
    from decision_model.learning import save_bundle
    from decision_model.prediction import PredictionService, ModelNotReady
    import decision_model.prediction as prediction
    save_bundle(tmp_path, np.ones(2), dict.fromkeys(['noul', 'choice', 'score'], 1.),
                {'encoder_id': 'test', 'encoder_revision': 'a'*40, 'hidden_size': 2, 'stage': 'trained'}, {})
    def forbidden(*args, **kwargs):
        raise AssertionError('Unfinished artifacts must not initialize an encoder')
    monkeypatch.setattr(prediction, 'CandidateEncoder', forbidden)
    with pytest.raises(ModelNotReady):
        PredictionService.load(tmp_path)