salute-api 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
salute_api/matchers.py ADDED
@@ -0,0 +1,120 @@
1
+ """Request matchers used by user-scenario trees."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Callable
7
+ from typing import Any
8
+
9
+ from salute_api.request import SaluteRequest
10
+
11
+ Matcher = Callable[[SaluteRequest], bool]
12
+
13
+
14
+ def compare(expected: Any, actual: Any) -> bool:
15
+ if type(expected) is not type(actual) and not (
16
+ isinstance(expected, dict) and isinstance(actual, dict)
17
+ ):
18
+ if not isinstance(expected, dict | list) and not isinstance(actual, dict | list):
19
+ return expected == actual
20
+ if type(expected) is not type(actual):
21
+ return False
22
+ if not isinstance(expected, dict | list) or expected is None:
23
+ return expected == actual
24
+ if isinstance(expected, list):
25
+ if not isinstance(actual, list):
26
+ return False
27
+ return all(any(compare(exp, act) for act in actual) for exp in expected)
28
+ if not isinstance(actual, dict):
29
+ return False
30
+ for key, expected_value in expected.items():
31
+ actual_value = actual.get(key)
32
+ if isinstance(expected_value, dict) and actual_value is not None:
33
+ if not compare(expected_value, actual_value):
34
+ return False
35
+ continue
36
+ if isinstance(expected_value, bool):
37
+ if expected_value == (actual_value is None):
38
+ return False
39
+ continue
40
+ if actual_value != expected_value:
41
+ return False
42
+ return True
43
+
44
+
45
+ def create_matchers() -> dict[str, Callable[..., Matcher]]:
46
+ def intent(expected: str, *, confidence: float = 0.7) -> Matcher:
47
+ def match(req: SaluteRequest) -> bool:
48
+ variants = req.inference.variants if req.inference else []
49
+ if not variants:
50
+ return False
51
+ for variant in variants:
52
+ if variant.intent.path == expected and variant.confidence >= confidence:
53
+ req.set_variant(variant)
54
+ return True
55
+ return False
56
+
57
+ return match
58
+
59
+ def text(expected: str, *, normalized: bool = False) -> Matcher:
60
+ def match(req: SaluteRequest) -> bool:
61
+ message = req.message
62
+ test_text = (
63
+ message.get("human_normalized_text") if normalized else message.get("original_text")
64
+ )
65
+ return expected == test_text
66
+
67
+ return match
68
+
69
+ def state(expected: dict[str, Any]) -> Matcher:
70
+ def match(req: SaluteRequest) -> bool:
71
+ return compare(expected, req.state)
72
+
73
+ return match
74
+
75
+ def action(expected: str) -> Matcher:
76
+ def match(req: SaluteRequest) -> bool:
77
+ server_action = req.server_action or {}
78
+ return server_action.get("type") == expected
79
+
80
+ return match
81
+
82
+ def regexp(pattern: str | re.Pattern[str], *, normalized: bool = True) -> Matcher:
83
+ compiled = re.compile(pattern) if isinstance(pattern, str) else pattern
84
+
85
+ def match(req: SaluteRequest) -> bool:
86
+ message = req.message
87
+ test_text = (
88
+ message.get("human_normalized_text") if normalized else message.get("original_text")
89
+ ) or ""
90
+ result = compiled.search(test_text)
91
+ if result is None:
92
+ return False
93
+ if result.groupdict():
94
+ req.variables.update(result.groupdict())
95
+ return True
96
+
97
+ return match
98
+
99
+ def match(*matchers: Matcher) -> Matcher:
100
+ def combined(req: SaluteRequest) -> bool:
101
+ return all(matcher(req) for matcher in matchers)
102
+
103
+ return combined
104
+
105
+ def legacy_action(expected: str) -> Matcher:
106
+ def match(req: SaluteRequest) -> bool:
107
+ server_action = req.server_action or {}
108
+ return server_action.get("action_id") == expected
109
+
110
+ return match
111
+
112
+ return {
113
+ "match": match,
114
+ "intent": intent,
115
+ "text": text,
116
+ "state": state,
117
+ "action": action,
118
+ "regexp": regexp,
119
+ "legacy_action": legacy_action,
120
+ }
salute_api/metrics.py ADDED
@@ -0,0 +1,114 @@
1
+ """Metrics sender: increment / timing / error, with an optional Sentry backend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Protocol
6
+
7
+
8
+ class MetricsSender(Protocol):
9
+ def increment(
10
+ self,
11
+ name: str,
12
+ value: int = 1,
13
+ tags: dict[str, Any] | None = None,
14
+ ) -> None: ...
15
+
16
+ def timing(
17
+ self,
18
+ name: str,
19
+ value_ms: float,
20
+ tags: dict[str, Any] | None = None,
21
+ ) -> None: ...
22
+
23
+ def error(
24
+ self,
25
+ name: str,
26
+ exc: BaseException | None = None,
27
+ tags: dict[str, Any] | None = None,
28
+ ) -> None: ...
29
+
30
+
31
+ class NoOpMetricsSender:
32
+ def increment(
33
+ self,
34
+ name: str,
35
+ value: int = 1,
36
+ tags: dict[str, Any] | None = None,
37
+ ) -> None:
38
+ del name, value, tags
39
+
40
+ def timing(
41
+ self,
42
+ name: str,
43
+ value_ms: float,
44
+ tags: dict[str, Any] | None = None,
45
+ ) -> None:
46
+ del name, value_ms, tags
47
+
48
+ def error(
49
+ self,
50
+ name: str,
51
+ exc: BaseException | None = None,
52
+ tags: dict[str, Any] | None = None,
53
+ ) -> None:
54
+ del name, exc, tags
55
+
56
+
57
+ class SentryMetricsSender:
58
+ def increment(
59
+ self,
60
+ name: str,
61
+ value: int = 1,
62
+ tags: dict[str, Any] | None = None,
63
+ ) -> None:
64
+ import sentry_sdk
65
+
66
+ sentry_sdk.add_breadcrumb(
67
+ category="metric",
68
+ message=name,
69
+ level="info",
70
+ data={"kind": "increment", "value": value, **(tags or {})},
71
+ )
72
+
73
+ def timing(
74
+ self,
75
+ name: str,
76
+ value_ms: float,
77
+ tags: dict[str, Any] | None = None,
78
+ ) -> None:
79
+ import sentry_sdk
80
+
81
+ sentry_sdk.add_breadcrumb(
82
+ category="metric",
83
+ message=name,
84
+ level="info",
85
+ data={"kind": "timing", "value_ms": value_ms, **(tags or {})},
86
+ )
87
+
88
+ def error(
89
+ self,
90
+ name: str,
91
+ exc: BaseException | None = None,
92
+ tags: dict[str, Any] | None = None,
93
+ ) -> None:
94
+ import sentry_sdk
95
+
96
+ sentry_sdk.add_breadcrumb(
97
+ category="metric",
98
+ message=name,
99
+ level="error",
100
+ data=tags or {},
101
+ )
102
+ if exc is not None:
103
+ sentry_sdk.capture_exception(exc)
104
+ else:
105
+ sentry_sdk.capture_message(name, level="error")
106
+
107
+
108
+ def create_metrics_sender(*, sentry_dsn: str | None = None) -> MetricsSender:
109
+ if sentry_dsn:
110
+ import sentry_sdk
111
+
112
+ sentry_sdk.init(dsn=sentry_dsn, send_default_pii=False)
113
+ return SentryMetricsSender()
114
+ return NoOpMetricsSender()
salute_api/models.py ADDED
@@ -0,0 +1,116 @@
1
+ """Pydantic models for the Salute NLP HTTP contract.
2
+
3
+ Field names and nesting match the example scenario's message shape
4
+ (`MESSAGE_TO_SKILL` in, `ANSWER_TO_USER` out). Unknown fields are kept.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from pydantic import BaseModel, ConfigDict, Field
12
+
13
+
14
+ class ExtraModel(BaseModel):
15
+ model_config = ConfigDict(extra="allow")
16
+
17
+
18
+ class Uuid(ExtraModel):
19
+ userId: str | None = None
20
+ sub: str | None = None
21
+ userChannel: str | None = None
22
+
23
+
24
+ class Character(ExtraModel):
25
+ id: str | None = None
26
+ name: str | None = None
27
+ gender: str | None = None
28
+ appeal: str | None = None
29
+
30
+
31
+ class Device(ExtraModel):
32
+ deviceId: str | None = None
33
+ surface: str | None = None
34
+ surfaceVersion: str | None = None
35
+ platformType: str | None = None
36
+ platformVersion: str | None = None
37
+ deviceManufacturer: str | None = None
38
+ deviceModel: str | None = None
39
+ capabilities: dict[str, Any] | None = None
40
+
41
+
42
+ class Message(ExtraModel):
43
+ original_text: str | None = None
44
+ asr_normalized_message: str | None = None
45
+ normalized_text: str | None = None
46
+ human_normalized_text: str | None = None
47
+
48
+
49
+ class ServerAction(ExtraModel):
50
+ type: str | None = None
51
+ action_id: str | None = None
52
+ payload: dict[str, Any] | None = None
53
+ parameters: dict[str, Any] | None = None
54
+
55
+
56
+ class NlpPayload(ExtraModel):
57
+ intent: str | None = None
58
+ original_intent: str | None = None
59
+ message: Message | None = None
60
+ character: Character | None = None
61
+ device: Device | None = None
62
+ meta: dict[str, Any] | None = None
63
+ projectName: str | None = None
64
+ server_action: ServerAction | dict[str, Any] | None = None
65
+ app_info: dict[str, Any] | None = None
66
+
67
+
68
+ class SaluteNlpRequest(ExtraModel):
69
+ """Incoming Dialog Policy NLP body (`MESSAGE_TO_SKILL` and related)."""
70
+
71
+ messageName: str | None = None
72
+ messageId: Any = None
73
+ sessionId: str | None = None
74
+ uuid: Uuid | None = None
75
+ payload: NlpPayload | None = None
76
+
77
+
78
+ class Bubble(ExtraModel):
79
+ text: str
80
+ expand_policy: str = "auto_expand"
81
+ markdown: bool = False
82
+
83
+
84
+ class SuggestionButton(ExtraModel):
85
+ title: str | None = None
86
+ action: dict[str, Any] | None = None
87
+ message_name: str | None = None
88
+
89
+
90
+ class Suggestions(ExtraModel):
91
+ buttons: list[SuggestionButton | dict[str, Any]] = Field(default_factory=list)
92
+
93
+
94
+ class AnswerPayload(ExtraModel):
95
+ device: Device | dict[str, Any] | None = None
96
+ projectName: str | None = None
97
+ items: list[dict[str, Any]] = Field(default_factory=list)
98
+ finished: bool = False
99
+ intent: str | None = "scenario"
100
+ pronounceText: str | None = None
101
+ pronounceTextType: str | None = None
102
+ auto_listening: bool | None = None
103
+ suggestions: Suggestions | dict[str, Any] | None = None
104
+ emotion: dict[str, Any] | None = None
105
+ asr_hints: dict[str, Any] | None = None
106
+ led_display: dict[str, Any] | None = None
107
+
108
+
109
+ class SaluteNlpResponse(ExtraModel):
110
+ """Outgoing NLP body (`ANSWER_TO_USER`, `POLICY_RUN_APP`, …)."""
111
+
112
+ messageName: str | None = None
113
+ messageId: Any = None
114
+ sessionId: str | None = None
115
+ uuid: Uuid | dict[str, Any] | None = None
116
+ payload: AnswerPayload | dict[str, Any] | None = None
salute_api/process.py ADDED
@@ -0,0 +1,61 @@
1
+ """PRE/POST process binding for scenario handlers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from collections.abc import Callable, Sequence
7
+ from dataclasses import dataclass, replace
8
+ from enum import StrEnum
9
+ from typing import Any
10
+
11
+ from salute_api.scenario import Dispatch, Handler, ScenarioContext, ScenarioSchema
12
+
13
+
14
+ class ProcessType(StrEnum):
15
+ PRE = "PRE"
16
+ POST = "POST"
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class BoundProcess:
21
+ func: Callable[..., Any]
22
+ type: ProcessType
23
+
24
+
25
+ async def _run(func: Callable[..., Any], ctx: ScenarioContext, dispatch: Dispatch) -> None:
26
+ result = func(ctx, dispatch)
27
+ if inspect.isawaitable(result):
28
+ await result
29
+
30
+
31
+ def bind_process(schema: ScenarioSchema, processes: Sequence[BoundProcess]) -> ScenarioSchema:
32
+ if not schema:
33
+ return schema
34
+
35
+ pre = [item.func for item in processes if item.type is ProcessType.PRE]
36
+ post = [item.func for item in processes if item.type is ProcessType.POST]
37
+ next_map: ScenarioSchema = {}
38
+
39
+ for key, state in schema.items():
40
+ original = state.handle
41
+
42
+ async def wrapped(
43
+ ctx: ScenarioContext,
44
+ dispatch: Dispatch,
45
+ *,
46
+ _original: Handler = original,
47
+ _pre: list[Callable[..., Any]] = pre,
48
+ _post: list[Callable[..., Any]] = post,
49
+ ) -> None:
50
+ for func in _pre:
51
+ await _run(func, ctx, dispatch)
52
+ result = _original(ctx, dispatch)
53
+ if inspect.isawaitable(result):
54
+ await result
55
+ for func in _post:
56
+ await _run(func, ctx, dispatch)
57
+
58
+ children = bind_process(state.children, processes) if state.children else None
59
+ next_map[key] = replace(state, handle=wrapped, children=children)
60
+
61
+ return next_map
salute_api/py.typed ADDED
File without changes
@@ -0,0 +1,222 @@
1
+ """Intent recognizers: local phrase matching and SmartApp Brain."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Protocol
6
+
7
+ from salute_api.logging import logger
8
+ from salute_api.request import SaluteRequest
9
+ from salute_api.response import SaluteResponse
10
+ from salute_api.types import FoundSlot, Inference, Intent, IntentSlot, SaluteSession, Variant
11
+
12
+
13
+ class Recognizer(Protocol):
14
+ async def inference(
15
+ self,
16
+ *,
17
+ req: SaluteRequest,
18
+ res: SaluteResponse | None = None,
19
+ session: SaluteSession | None = None,
20
+ ) -> None: ...
21
+
22
+
23
+ def _normalize(text: str) -> str:
24
+ return " ".join(text.strip().lower().split())
25
+
26
+
27
+ def _entity_value(entities: dict[str, Any], entity_name: str, text: str) -> str | None:
28
+ spec = entities.get(entity_name) or {}
29
+ haystack = _normalize(text)
30
+ for matcher in spec.get("matchers") or []:
31
+ if matcher.get("type") != "synonyms":
32
+ continue
33
+ for rule in matcher.get("rule") or []:
34
+ if _normalize(str(rule)) == haystack:
35
+ value = matcher.get("value")
36
+ return "" if value is None else str(value)
37
+ return None
38
+
39
+
40
+ def _phrase_matches(rule: str, text: str, entities: dict[str, Any]) -> dict[str, str] | None:
41
+ normalized_rule = rule.strip()
42
+ if normalized_rule.startswith("@"):
43
+ names = [part[1:] for part in normalized_rule.split() if part.startswith("@")]
44
+ if not names:
45
+ return None
46
+ slots: dict[str, str] = {}
47
+ for name in names:
48
+ value = _entity_value(entities, name, text)
49
+ if value is None:
50
+ return None
51
+ slots[name] = value
52
+ return slots
53
+ if _normalize(rule) == _normalize(text):
54
+ return {}
55
+ return None
56
+
57
+
58
+ class IntentsRecognizer:
59
+ """Local phrase/entity recognizer backed by an intents.json model.
60
+
61
+ Useful for tests, local development, and other quiz-style apps that share
62
+ the same SmartApp Brain intent format.
63
+ """
64
+
65
+ def __init__(self, model: dict[str, Any]) -> None:
66
+ self.intents = model.get("intents") or {}
67
+ self.entities = model.get("entities") or {}
68
+
69
+ async def inference(
70
+ self,
71
+ *,
72
+ req: SaluteRequest,
73
+ res: SaluteResponse | None = None,
74
+ session: SaluteSession | None = None,
75
+ ) -> None:
76
+ del res, session
77
+ text = (req.message.get("original_text") or "").strip()
78
+ variants: list[Variant] = []
79
+ for path, spec in self.intents.items():
80
+ matched_slots: dict[str, str] | None = None
81
+ for matcher in spec.get("matchers") or []:
82
+ if matcher.get("type") != "phrase":
83
+ continue
84
+ matched_slots = _phrase_matches(str(matcher.get("rule") or ""), text, self.entities)
85
+ if matched_slots is not None:
86
+ break
87
+ if matched_slots is None:
88
+ continue
89
+ variables = spec.get("variables") or {}
90
+ intent_slots = [
91
+ IntentSlot(
92
+ name=name,
93
+ entity=var.get("entity") or name,
94
+ required=bool(var.get("required")),
95
+ prompts=list(var.get("questions") or []),
96
+ array=bool(var.get("array")),
97
+ )
98
+ for name, var in variables.items()
99
+ ]
100
+ found = [
101
+ FoundSlot(name=name, value=value)
102
+ for name, value in matched_slots.items()
103
+ if name in variables or name == "answer"
104
+ ]
105
+ if "answer" in matched_slots and "answer" in variables:
106
+ found = [FoundSlot(name="answer", value=matched_slots["answer"])]
107
+ variants.append(
108
+ Variant(
109
+ intent=Intent(path=path, slots=intent_slots),
110
+ confidence=1.0,
111
+ slots=found,
112
+ )
113
+ )
114
+ req.set_inference(Inference(variants=variants))
115
+ logger.debug(
116
+ "intents recognizer",
117
+ extra={
118
+ "originalText": text,
119
+ "variantPaths": [variant.intent.path for variant in variants],
120
+ },
121
+ )
122
+
123
+
124
+ class SmartAppBrainRecognizer:
125
+ def __init__(
126
+ self,
127
+ access_token: str,
128
+ host: str = "https://smartapp-code.sberdevices.ru",
129
+ *,
130
+ n_best: int = 1,
131
+ timeout: float = 5.0,
132
+ ) -> None:
133
+ if not access_token:
134
+ raise ValueError("Wrong SmartApp Brain token.")
135
+ self.access_token = access_token
136
+ self.host = host.rstrip("/")
137
+ self.n_best = n_best
138
+ self.timeout = timeout
139
+
140
+ def _url(self, path: str) -> str:
141
+ return f"{self.host}/cailapub/api/caila/p/{self.access_token}{path}"
142
+
143
+ async def ask(self, path: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
144
+ import httpx
145
+
146
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
147
+ response = await client.post(
148
+ self._url(path),
149
+ json=payload,
150
+ headers={"Content-Type": "application/json", "accept": "application/json"},
151
+ )
152
+ response.raise_for_status()
153
+ return response.json()
154
+
155
+ async def inference(
156
+ self,
157
+ *,
158
+ req: SaluteRequest,
159
+ res: SaluteResponse | None = None,
160
+ session: SaluteSession | None = None,
161
+ ) -> None:
162
+ del res, session
163
+ if not req.message:
164
+ return
165
+ phrase = req.message.get("original_text") or ""
166
+ try:
167
+ data = await self.ask(
168
+ "/nlu/inference",
169
+ {
170
+ "phrase": {"text": phrase},
171
+ "nBest": self.n_best,
172
+ "showDebugInfo": False,
173
+ },
174
+ )
175
+ except Exception:
176
+ logger.exception("smartapp brain inference failed", extra={"originalText": phrase})
177
+ raise
178
+ inference = _inference_from_brain(data)
179
+ req.set_inference(inference)
180
+ logger.debug(
181
+ "smartapp brain inference",
182
+ extra={
183
+ "originalText": phrase,
184
+ "variantPaths": [variant.intent.path for variant in inference.variants],
185
+ },
186
+ )
187
+
188
+
189
+ def _inference_from_brain(data: dict[str, Any]) -> Inference:
190
+ variants: list[Variant] = []
191
+ for raw in data.get("variants") or []:
192
+ raw_intent = raw.get("intent") or {}
193
+ slots = [
194
+ FoundSlot(
195
+ name=slot.get("name") or "",
196
+ value=slot.get("value"),
197
+ array=bool(slot.get("array")),
198
+ )
199
+ for slot in raw.get("slots") or []
200
+ ]
201
+ intent_slots = [
202
+ IntentSlot(
203
+ name=item.get("name") or "",
204
+ entity=item.get("entity"),
205
+ required=bool(item.get("required")),
206
+ prompts=list(item.get("prompts") or []),
207
+ array=bool(item.get("array")),
208
+ )
209
+ for item in raw_intent.get("slots") or []
210
+ ]
211
+ variants.append(
212
+ Variant(
213
+ intent=Intent(
214
+ path=raw_intent.get("path") or "",
215
+ id=int(raw_intent.get("id") or 0),
216
+ slots=intent_slots,
217
+ ),
218
+ confidence=float(raw.get("confidence") or 0),
219
+ slots=slots,
220
+ )
221
+ )
222
+ return Inference(variants=variants)