paisa-parse 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.
- paisa_parse/__init__.py +37 -0
- paisa_parse/cli.py +102 -0
- paisa_parse/engine.py +141 -0
- paisa_parse/integrations/__init__.py +28 -0
- paisa_parse/integrations/livekit.py +132 -0
- paisa_parse/integrations/mcp_server.py +95 -0
- paisa_parse/integrations/pipecat.py +101 -0
- paisa_parse/lexicon.py +620 -0
- paisa_parse/parsers/__init__.py +8 -0
- paisa_parse/parsers/amount.py +495 -0
- paisa_parse/parsers/digits.py +275 -0
- paisa_parse/parsers/ifsc.py +429 -0
- paisa_parse/parsers/upi.py +599 -0
- paisa_parse/policy.py +180 -0
- paisa_parse/types.py +113 -0
- paisa_parse-0.1.0.dist-info/METADATA +202 -0
- paisa_parse-0.1.0.dist-info/RECORD +20 -0
- paisa_parse-0.1.0.dist-info/WHEEL +4 -0
- paisa_parse-0.1.0.dist-info/entry_points.txt +3 -0
- paisa_parse-0.1.0.dist-info/licenses/LICENSE +21 -0
paisa_parse/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""paisa-parse: Hinglish & Indian-English spoken financial entity parser."""
|
|
2
|
+
|
|
3
|
+
from paisa_parse.engine import (
|
|
4
|
+
parse,
|
|
5
|
+
parse_amount,
|
|
6
|
+
parse_digit_strings,
|
|
7
|
+
parse_ifsc_codes,
|
|
8
|
+
parse_upi_ids,
|
|
9
|
+
)
|
|
10
|
+
from paisa_parse.lexicon import amount_to_words_en_in, format_inr
|
|
11
|
+
from paisa_parse.policy import ConfirmPolicy
|
|
12
|
+
from paisa_parse.types import (
|
|
13
|
+
ConfirmAction,
|
|
14
|
+
EntitySpan,
|
|
15
|
+
EntityType,
|
|
16
|
+
ParsedEntity,
|
|
17
|
+
ParseResult,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"__version__",
|
|
24
|
+
"ConfirmAction",
|
|
25
|
+
"ConfirmPolicy",
|
|
26
|
+
"EntitySpan",
|
|
27
|
+
"EntityType",
|
|
28
|
+
"ParseResult",
|
|
29
|
+
"ParsedEntity",
|
|
30
|
+
"amount_to_words_en_in",
|
|
31
|
+
"format_inr",
|
|
32
|
+
"parse",
|
|
33
|
+
"parse_amount",
|
|
34
|
+
"parse_digit_strings",
|
|
35
|
+
"parse_ifsc_codes",
|
|
36
|
+
"parse_upi_ids",
|
|
37
|
+
]
|
paisa_parse/cli.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Command-line interface for paisa-parse."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import contextlib
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
|
|
11
|
+
from paisa_parse.engine import parse
|
|
12
|
+
from paisa_parse.policy import ConfirmPolicy
|
|
13
|
+
from paisa_parse.types import EntityType
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _configure_utf8_stdio() -> None:
|
|
17
|
+
for stream in (sys.stdout, sys.stderr):
|
|
18
|
+
if hasattr(stream, "reconfigure"):
|
|
19
|
+
with contextlib.suppress(Exception):
|
|
20
|
+
stream.reconfigure(encoding="utf-8")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _make_policy(name: str, language: str) -> ConfirmPolicy:
|
|
24
|
+
lang = "hinglish" if language == "hinglish" else "en-IN"
|
|
25
|
+
if name == "strict":
|
|
26
|
+
return ConfirmPolicy.strict(language=lang)
|
|
27
|
+
if name == "permissive":
|
|
28
|
+
return ConfirmPolicy.permissive(language=lang)
|
|
29
|
+
return ConfirmPolicy.balanced(language=lang)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
33
|
+
parser = argparse.ArgumentParser(
|
|
34
|
+
prog="paisa-parse",
|
|
35
|
+
description="Parse Hinglish & Indian-English spoken financial entities with confidence scores.",
|
|
36
|
+
)
|
|
37
|
+
parser.add_argument(
|
|
38
|
+
"text",
|
|
39
|
+
help="Input utterance/transcript to parse.",
|
|
40
|
+
)
|
|
41
|
+
parser.add_argument(
|
|
42
|
+
"--policy",
|
|
43
|
+
choices=("balanced", "strict", "permissive"),
|
|
44
|
+
default="balanced",
|
|
45
|
+
help="Confirm-back policy preset (default: balanced).",
|
|
46
|
+
)
|
|
47
|
+
parser.add_argument(
|
|
48
|
+
"--lang",
|
|
49
|
+
choices=("en-IN", "hinglish"),
|
|
50
|
+
default="en-IN",
|
|
51
|
+
help="Confirm-back prompt language (default: en-IN).",
|
|
52
|
+
)
|
|
53
|
+
parser.add_argument(
|
|
54
|
+
"--kinds",
|
|
55
|
+
default=None,
|
|
56
|
+
help="Comma-separated entity kinds to extract (amount,digits,upi_id,ifsc).",
|
|
57
|
+
)
|
|
58
|
+
parser.add_argument(
|
|
59
|
+
"--json",
|
|
60
|
+
action="store_true",
|
|
61
|
+
dest="as_json",
|
|
62
|
+
help="Emit structured JSON output.",
|
|
63
|
+
)
|
|
64
|
+
return parser
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
68
|
+
_configure_utf8_stdio()
|
|
69
|
+
parser = build_parser()
|
|
70
|
+
args = parser.parse_args(list(argv) if argv is not None else None)
|
|
71
|
+
|
|
72
|
+
policy = _make_policy(args.policy, args.lang)
|
|
73
|
+
kinds = (
|
|
74
|
+
[EntityType(k.strip()) for k in args.kinds.split(",") if k.strip()]
|
|
75
|
+
if args.kinds
|
|
76
|
+
else None
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
result = parse(args.text, policy=policy, kinds=kinds)
|
|
80
|
+
if args.as_json:
|
|
81
|
+
print(json.dumps(result.to_dict(), ensure_ascii=False, indent=2))
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
print(f"Input: {result.text}")
|
|
85
|
+
print(f"Normalized: {result.normalized_text}")
|
|
86
|
+
if not result.entities:
|
|
87
|
+
print("Entities: (none)")
|
|
88
|
+
return 0
|
|
89
|
+
|
|
90
|
+
print(f"Entities ({len(result.entities)}):")
|
|
91
|
+
for idx, ent in enumerate(result.entities, start=1):
|
|
92
|
+
print(
|
|
93
|
+
f" {idx}. [{ent.kind.value}] {ent.formatted} "
|
|
94
|
+
f"(raw={ent.span.raw!r}, conf={ent.confidence:.2f}, action={ent.action.value})"
|
|
95
|
+
)
|
|
96
|
+
if ent.confirm_prompt:
|
|
97
|
+
print(f" prompt: {ent.confirm_prompt}")
|
|
98
|
+
return 0
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
if __name__ == "__main__":
|
|
102
|
+
raise SystemExit(main())
|
paisa_parse/engine.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Unified parsing orchestrator, overlap resolution, and normalized text builder."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
|
|
7
|
+
from paisa_parse.parsers.amount import parse_amounts
|
|
8
|
+
from paisa_parse.parsers.digits import parse_digits
|
|
9
|
+
from paisa_parse.parsers.ifsc import parse_ifsc
|
|
10
|
+
from paisa_parse.parsers.upi import parse_upi
|
|
11
|
+
from paisa_parse.policy import ConfirmPolicy
|
|
12
|
+
from paisa_parse.types import ConfirmAction, EntityType, ParsedEntity, ParseResult
|
|
13
|
+
|
|
14
|
+
_SPECIFICITY_RANK: dict[EntityType, int] = {
|
|
15
|
+
EntityType.UPI_ID: 4,
|
|
16
|
+
EntityType.IFSC: 3,
|
|
17
|
+
EntityType.AMOUNT: 2,
|
|
18
|
+
EntityType.DIGITS: 1,
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _overlaps(a: ParsedEntity, b: ParsedEntity) -> bool:
|
|
23
|
+
return a.span.start < b.span.end and a.span.end > b.span.start
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _priority_key(entity: ParsedEntity) -> tuple[int, int, int, float]:
|
|
27
|
+
span_len = entity.span.end - entity.span.start
|
|
28
|
+
if entity.kind == EntityType.AMOUNT:
|
|
29
|
+
has_scale_or_curr = bool(
|
|
30
|
+
entity.metadata.get("has_scale") or entity.metadata.get("has_currency")
|
|
31
|
+
)
|
|
32
|
+
# An amount with explicit scale/currency outranks DIGITS on overlap;
|
|
33
|
+
# a bare context-only number yields to a longer spoken DIGITS sequence.
|
|
34
|
+
amt_boost = 1 if has_scale_or_curr else 0
|
|
35
|
+
else:
|
|
36
|
+
amt_boost = 1
|
|
37
|
+
return (
|
|
38
|
+
_SPECIFICITY_RANK[entity.kind] + (1 if amt_boost and entity.kind == EntityType.AMOUNT else 0),
|
|
39
|
+
span_len,
|
|
40
|
+
1 if entity.metadata.get("known_handle") or entity.metadata.get("known_bank") else 0,
|
|
41
|
+
entity.confidence,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _resolve_overlaps(candidates: list[ParsedEntity]) -> list[ParsedEntity]:
|
|
46
|
+
"""Resolve overlapping entity spans deterministically by specificity and length."""
|
|
47
|
+
ordered = sorted(candidates, key=_priority_key, reverse=True)
|
|
48
|
+
accepted: list[ParsedEntity] = []
|
|
49
|
+
for cand in ordered:
|
|
50
|
+
if any(_overlaps(cand, kept) for kept in accepted):
|
|
51
|
+
continue
|
|
52
|
+
accepted.append(cand)
|
|
53
|
+
accepted.sort(key=lambda e: e.span.start)
|
|
54
|
+
return accepted
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _build_normalized_text(text: str, entities: list[ParsedEntity]) -> str:
|
|
58
|
+
if not entities:
|
|
59
|
+
return text
|
|
60
|
+
parts: list[str] = []
|
|
61
|
+
cursor = 0
|
|
62
|
+
for ent in entities:
|
|
63
|
+
if ent.span.start < cursor:
|
|
64
|
+
continue
|
|
65
|
+
parts.append(text[cursor : ent.span.start])
|
|
66
|
+
if ent.action == ConfirmAction.REPROMPT:
|
|
67
|
+
parts.append(ent.span.raw)
|
|
68
|
+
else:
|
|
69
|
+
parts.append(ent.formatted)
|
|
70
|
+
cursor = ent.span.end
|
|
71
|
+
parts.append(text[cursor:])
|
|
72
|
+
return "".join(parts)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parse(
|
|
76
|
+
text: str,
|
|
77
|
+
*,
|
|
78
|
+
policy: ConfirmPolicy | None = None,
|
|
79
|
+
kinds: Iterable[EntityType | str] | None = None,
|
|
80
|
+
) -> ParseResult:
|
|
81
|
+
"""Parse all Hinglish/Indian-English financial entities from `text`.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
text: Input transcript or user message.
|
|
85
|
+
policy: Confirmation policy; defaults to `ConfirmPolicy.balanced()`.
|
|
86
|
+
kinds: Optional subset of entity types to extract.
|
|
87
|
+
"""
|
|
88
|
+
active_policy = policy if policy is not None else ConfirmPolicy.balanced()
|
|
89
|
+
allowed: set[EntityType] | None = (
|
|
90
|
+
{EntityType(k) for k in kinds} if kinds is not None else None
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
def want(kind: EntityType) -> bool:
|
|
94
|
+
return allowed is None or kind in allowed
|
|
95
|
+
|
|
96
|
+
candidates: list[ParsedEntity] = []
|
|
97
|
+
if want(EntityType.UPI_ID):
|
|
98
|
+
candidates.extend(parse_upi(text))
|
|
99
|
+
if want(EntityType.IFSC):
|
|
100
|
+
candidates.extend(parse_ifsc(text))
|
|
101
|
+
|
|
102
|
+
# Suppress amount/digit candidates that collide with already-found UPI/IFSC spans
|
|
103
|
+
structured_spans = [(e.span.start, e.span.end) for e in candidates]
|
|
104
|
+
|
|
105
|
+
def hits_structured(ent: ParsedEntity) -> bool:
|
|
106
|
+
return any(ent.span.start < se and ent.span.end > ss for ss, se in structured_spans)
|
|
107
|
+
|
|
108
|
+
if want(EntityType.AMOUNT):
|
|
109
|
+
candidates.extend(e for e in parse_amounts(text) if not hits_structured(e))
|
|
110
|
+
if want(EntityType.DIGITS):
|
|
111
|
+
candidates.extend(e for e in parse_digits(text) if not hits_structured(e))
|
|
112
|
+
|
|
113
|
+
resolved = _resolve_overlaps(candidates)
|
|
114
|
+
evaluated = [active_policy.evaluate(ent) for ent in resolved]
|
|
115
|
+
normalized = _build_normalized_text(text, evaluated)
|
|
116
|
+
|
|
117
|
+
return ParseResult(
|
|
118
|
+
text=text,
|
|
119
|
+
entities=tuple(evaluated),
|
|
120
|
+
normalized_text=normalized,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def parse_amount(text: str, *, policy: ConfirmPolicy | None = None) -> list[ParsedEntity]:
|
|
125
|
+
"""Convenience wrapper returning evaluated AMOUNT entities."""
|
|
126
|
+
return list(parse(text, policy=policy, kinds=(EntityType.AMOUNT,)).entities)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def parse_digit_strings(text: str, *, policy: ConfirmPolicy | None = None) -> list[ParsedEntity]:
|
|
130
|
+
"""Convenience wrapper returning evaluated DIGITS entities."""
|
|
131
|
+
return list(parse(text, policy=policy, kinds=(EntityType.DIGITS,)).entities)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def parse_upi_ids(text: str, *, policy: ConfirmPolicy | None = None) -> list[ParsedEntity]:
|
|
135
|
+
"""Convenience wrapper returning evaluated UPI_ID entities."""
|
|
136
|
+
return list(parse(text, policy=policy, kinds=(EntityType.UPI_ID,)).entities)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def parse_ifsc_codes(text: str, *, policy: ConfirmPolicy | None = None) -> list[ParsedEntity]:
|
|
140
|
+
"""Convenience wrapper returning evaluated IFSC entities."""
|
|
141
|
+
return list(parse(text, policy=policy, kinds=(EntityType.IFSC,)).entities)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Voice-agent and tool integrations for Pipecat, LiveKit Agents, and MCP."""
|
|
2
|
+
|
|
3
|
+
from paisa_parse.integrations.livekit import PaisaParseAgentMixin, PaisaParseHook
|
|
4
|
+
from paisa_parse.integrations.mcp_server import (
|
|
5
|
+
create_mcp_server,
|
|
6
|
+
tool_parse_amount,
|
|
7
|
+
tool_parse_financial_text,
|
|
8
|
+
tool_validate_ifsc_code,
|
|
9
|
+
tool_validate_upi_id,
|
|
10
|
+
)
|
|
11
|
+
from paisa_parse.integrations.pipecat import (
|
|
12
|
+
PaisaParseProcessor,
|
|
13
|
+
apply_pipecat_mode,
|
|
14
|
+
format_annotation,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"PaisaParseAgentMixin",
|
|
19
|
+
"PaisaParseHook",
|
|
20
|
+
"PaisaParseProcessor",
|
|
21
|
+
"apply_pipecat_mode",
|
|
22
|
+
"create_mcp_server",
|
|
23
|
+
"format_annotation",
|
|
24
|
+
"tool_parse_amount",
|
|
25
|
+
"tool_parse_financial_text",
|
|
26
|
+
"tool_validate_ifsc_code",
|
|
27
|
+
"tool_validate_upi_id",
|
|
28
|
+
]
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""LiveKit Agents integration hook & Agent mixin for paisa-parse."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import AsyncIterable, Callable, Iterable
|
|
8
|
+
from typing import Any, Literal
|
|
9
|
+
|
|
10
|
+
from paisa_parse.engine import parse
|
|
11
|
+
from paisa_parse.policy import ConfirmPolicy
|
|
12
|
+
from paisa_parse.types import EntityType, ParseResult
|
|
13
|
+
|
|
14
|
+
LiveKitMode = Literal["annotate", "replace", "callback_only"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _extract_message_text(message: Any) -> str:
|
|
18
|
+
content = getattr(message, "text_content", None)
|
|
19
|
+
if callable(content):
|
|
20
|
+
return str(content() or "")
|
|
21
|
+
if isinstance(content, str):
|
|
22
|
+
return content
|
|
23
|
+
raw = getattr(message, "content", "")
|
|
24
|
+
if isinstance(raw, str):
|
|
25
|
+
return raw
|
|
26
|
+
if isinstance(raw, list):
|
|
27
|
+
return " ".join(str(part) for part in raw if isinstance(part, str))
|
|
28
|
+
return ""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _build_system_guidance(result: ParseResult) -> str:
|
|
32
|
+
summary = [
|
|
33
|
+
{
|
|
34
|
+
"kind": e.kind.value,
|
|
35
|
+
"value": e.to_dict()["value"],
|
|
36
|
+
"formatted": e.formatted,
|
|
37
|
+
"confidence": round(e.confidence, 3),
|
|
38
|
+
"action": e.action.value,
|
|
39
|
+
"confirm_prompt": e.confirm_prompt,
|
|
40
|
+
}
|
|
41
|
+
for e in result.entities
|
|
42
|
+
]
|
|
43
|
+
guidance = (
|
|
44
|
+
"[paisa_parse] Parsed Indian financial entities: "
|
|
45
|
+
+ json.dumps(summary, ensure_ascii=False)
|
|
46
|
+
)
|
|
47
|
+
prompts = [e.confirm_prompt for e in result.entities if e.confirm_prompt]
|
|
48
|
+
if prompts:
|
|
49
|
+
guidance += " Confirmation policy advises asking the user: " + " | ".join(prompts)
|
|
50
|
+
return guidance
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class PaisaParseHook:
|
|
54
|
+
"""Reusable hook for LiveKit Agents `on_user_turn_completed` and `stt_node`."""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
*,
|
|
59
|
+
policy: ConfirmPolicy | None = None,
|
|
60
|
+
kinds: Iterable[EntityType | str] | None = None,
|
|
61
|
+
mode: LiveKitMode = "annotate",
|
|
62
|
+
inject_context: bool = True,
|
|
63
|
+
on_parsed: Callable[[ParseResult, Any, Any], Any] | None = None,
|
|
64
|
+
) -> None:
|
|
65
|
+
self.policy = policy if policy is not None else ConfirmPolicy.balanced()
|
|
66
|
+
self.kinds = tuple(kinds) if kinds is not None else None
|
|
67
|
+
self.mode: LiveKitMode = mode
|
|
68
|
+
self.inject_context = inject_context
|
|
69
|
+
self.on_parsed = on_parsed
|
|
70
|
+
self.last_result: ParseResult | None = None
|
|
71
|
+
|
|
72
|
+
async def on_user_turn_completed(self, turn_ctx: Any, new_message: Any) -> ParseResult:
|
|
73
|
+
"""Parse the finalized user message and optionally inject system guidance into `turn_ctx`."""
|
|
74
|
+
text = _extract_message_text(new_message)
|
|
75
|
+
result = parse(text, policy=self.policy, kinds=self.kinds)
|
|
76
|
+
self.last_result = result
|
|
77
|
+
|
|
78
|
+
if result.entities and self.inject_context and hasattr(turn_ctx, "add_message"):
|
|
79
|
+
turn_ctx.add_message(
|
|
80
|
+
role="system",
|
|
81
|
+
content=_build_system_guidance(result),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
if self.on_parsed is not None:
|
|
85
|
+
maybe_coro = self.on_parsed(result, turn_ctx, new_message)
|
|
86
|
+
if inspect.isawaitable(maybe_coro):
|
|
87
|
+
await maybe_coro
|
|
88
|
+
|
|
89
|
+
return result
|
|
90
|
+
|
|
91
|
+
async def wrap_stt_stream(self, stt_stream: AsyncIterable[Any]) -> AsyncIterable[Any]:
|
|
92
|
+
"""Wrap a LiveKit `stt_node` async stream to normalize final transcripts on the fly."""
|
|
93
|
+
async for event in stt_stream:
|
|
94
|
+
event_type = getattr(event, "type", None)
|
|
95
|
+
type_name = getattr(event_type, "name", str(event_type))
|
|
96
|
+
alternatives = getattr(event, "alternatives", None)
|
|
97
|
+
|
|
98
|
+
if "FINAL_TRANSCRIPT" in type_name and alternatives:
|
|
99
|
+
alt0 = alternatives[0]
|
|
100
|
+
raw_text = getattr(alt0, "text", "") or ""
|
|
101
|
+
result = parse(raw_text, policy=self.policy, kinds=self.kinds)
|
|
102
|
+
self.last_result = result
|
|
103
|
+
if result.entities and self.mode == "replace":
|
|
104
|
+
alt0.text = result.normalized_text
|
|
105
|
+
elif result.entities and self.mode == "annotate":
|
|
106
|
+
tag = "; ".join(f"{e.kind.value}={e.formatted}" for e in result.entities)
|
|
107
|
+
alt0.text = f"{raw_text} [paisa_parse: {tag}]".strip()
|
|
108
|
+
|
|
109
|
+
if self.on_parsed is not None:
|
|
110
|
+
maybe_coro = self.on_parsed(result, None, event)
|
|
111
|
+
if inspect.isawaitable(maybe_coro):
|
|
112
|
+
await maybe_coro
|
|
113
|
+
|
|
114
|
+
yield event
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class PaisaParseAgentMixin:
|
|
118
|
+
"""Mixin for `livekit.agents.Agent` subclasses to run paisa-parse on every user turn."""
|
|
119
|
+
|
|
120
|
+
paisa_hook: PaisaParseHook
|
|
121
|
+
|
|
122
|
+
def init_paisa_hook(self, **kwargs: Any) -> PaisaParseHook:
|
|
123
|
+
self.paisa_hook = PaisaParseHook(**kwargs)
|
|
124
|
+
return self.paisa_hook
|
|
125
|
+
|
|
126
|
+
async def on_user_turn_completed(self, turn_ctx: Any, new_message: Any) -> None:
|
|
127
|
+
if not hasattr(self, "paisa_hook"):
|
|
128
|
+
self.paisa_hook = PaisaParseHook()
|
|
129
|
+
await self.paisa_hook.on_user_turn_completed(turn_ctx, new_message)
|
|
130
|
+
super_method = getattr(super(), "on_user_turn_completed", None)
|
|
131
|
+
if super_method is not None:
|
|
132
|
+
await super_method(turn_ctx, new_message)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Model Context Protocol (MCP) stdio tool server for paisa-parse."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Literal
|
|
6
|
+
|
|
7
|
+
from paisa_parse.engine import parse
|
|
8
|
+
from paisa_parse.policy import ConfirmPolicy
|
|
9
|
+
from paisa_parse.types import EntityType
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _select_policy(
|
|
13
|
+
policy_mode: Literal["balanced", "strict", "permissive"],
|
|
14
|
+
language: Literal["en-IN", "hinglish"],
|
|
15
|
+
) -> ConfirmPolicy:
|
|
16
|
+
if policy_mode == "strict":
|
|
17
|
+
return ConfirmPolicy.strict(language=language)
|
|
18
|
+
if policy_mode == "permissive":
|
|
19
|
+
return ConfirmPolicy.permissive(language=language)
|
|
20
|
+
return ConfirmPolicy.balanced(language=language)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def tool_parse_financial_text(
|
|
24
|
+
text: str,
|
|
25
|
+
policy_mode: Literal["balanced", "strict", "permissive"] = "balanced",
|
|
26
|
+
language: Literal["en-IN", "hinglish"] = "en-IN",
|
|
27
|
+
) -> dict[str, Any]:
|
|
28
|
+
"""Parse all Hinglish/Indian-English financial entities (amounts, digits, UPI IDs, IFSC codes)."""
|
|
29
|
+
policy = _select_policy(policy_mode, language)
|
|
30
|
+
return parse(text, policy=policy).to_dict()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def tool_parse_amount(
|
|
34
|
+
text: str,
|
|
35
|
+
language: Literal["en-IN", "hinglish"] = "en-IN",
|
|
36
|
+
) -> dict[str, Any]:
|
|
37
|
+
"""Parse Hinglish or Indian-English spoken monetary amounts (e.g. 'dedh lakh', 'sava do crore')."""
|
|
38
|
+
policy = ConfirmPolicy.balanced(language=language)
|
|
39
|
+
return parse(text, policy=policy, kinds=(EntityType.AMOUNT,)).to_dict()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def tool_validate_upi_id(
|
|
43
|
+
text: str,
|
|
44
|
+
language: Literal["en-IN", "hinglish"] = "en-IN",
|
|
45
|
+
) -> dict[str, Any]:
|
|
46
|
+
"""Extract and validate a written or spoken UPI ID against known NPCI PSP handles."""
|
|
47
|
+
policy = ConfirmPolicy.balanced(language=language)
|
|
48
|
+
return parse(text, policy=policy, kinds=(EntityType.UPI_ID,)).to_dict()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def tool_validate_ifsc_code(
|
|
52
|
+
text: str,
|
|
53
|
+
language: Literal["en-IN", "hinglish"] = "en-IN",
|
|
54
|
+
) -> dict[str, Any]:
|
|
55
|
+
"""Extract and validate a written or spoken 11-character Indian IFSC code."""
|
|
56
|
+
policy = ConfirmPolicy.balanced(language=language)
|
|
57
|
+
return parse(text, policy=policy, kinds=(EntityType.IFSC,)).to_dict()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _import_fastmcp() -> Any:
|
|
61
|
+
try:
|
|
62
|
+
from mcp.server.fastmcp import FastMCP
|
|
63
|
+
|
|
64
|
+
return FastMCP
|
|
65
|
+
except ImportError:
|
|
66
|
+
try:
|
|
67
|
+
from fastmcp import FastMCP
|
|
68
|
+
|
|
69
|
+
return FastMCP
|
|
70
|
+
except ImportError as exc:
|
|
71
|
+
raise ImportError(
|
|
72
|
+
"MCP SDK is not installed. Install with: pip install 'paisa-parse[mcp]'"
|
|
73
|
+
) from exc
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def create_mcp_server(name: str = "paisa-parse") -> Any:
|
|
77
|
+
"""Create and configure a FastMCP server exposing paisa-parse tools."""
|
|
78
|
+
fastmcp_cls = _import_fastmcp()
|
|
79
|
+
mcp = fastmcp_cls(name)
|
|
80
|
+
|
|
81
|
+
mcp.tool()(tool_parse_financial_text)
|
|
82
|
+
mcp.tool()(tool_parse_amount)
|
|
83
|
+
mcp.tool()(tool_validate_upi_id)
|
|
84
|
+
mcp.tool()(tool_validate_ifsc_code)
|
|
85
|
+
return mcp
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def main() -> None:
|
|
89
|
+
"""Entrypoint for the `paisa-parse-mcp` stdio server."""
|
|
90
|
+
server = create_mcp_server()
|
|
91
|
+
server.run(transport="stdio")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
if __name__ == "__main__":
|
|
95
|
+
main()
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Pipecat FrameProcessor integration for paisa-parse."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
from collections.abc import Awaitable, Callable, Iterable
|
|
7
|
+
from typing import Any, Literal
|
|
8
|
+
|
|
9
|
+
from paisa_parse.engine import parse
|
|
10
|
+
from paisa_parse.policy import ConfirmPolicy
|
|
11
|
+
from paisa_parse.types import EntityType, ParseResult
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
from pipecat.frames.frames import Frame, TranscriptionFrame
|
|
15
|
+
from pipecat.processors.frame_processor import FrameDirection, FrameProcessor
|
|
16
|
+
|
|
17
|
+
_HAS_PIPECAT = True
|
|
18
|
+
except ImportError: # pragma: no cover - covered via fallback & mocked reload tests
|
|
19
|
+
_HAS_PIPECAT = False
|
|
20
|
+
Frame = Any # type: ignore[misc,assignment]
|
|
21
|
+
TranscriptionFrame = None # type: ignore[misc,assignment]
|
|
22
|
+
FrameDirection = Any # type: ignore[misc,assignment]
|
|
23
|
+
|
|
24
|
+
class FrameProcessor: # type: ignore[no-redef]
|
|
25
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
async def process_frame(self, frame: Any, direction: Any) -> None:
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
async def push_frame(self, frame: Any, direction: Any) -> None:
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
PipecatMode = Literal["annotate", "replace", "callback_only"]
|
|
36
|
+
ParsedCallback = Callable[[ParseResult, Any], Any | Awaitable[Any]]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def format_annotation(result: ParseResult) -> str:
|
|
40
|
+
"""Format a compact annotation block appended to Pipecat transcription frames."""
|
|
41
|
+
if not result.entities:
|
|
42
|
+
return ""
|
|
43
|
+
parts = [
|
|
44
|
+
f"{e.kind.value}={e.formatted} conf={e.confidence:.2f} action={e.action.value}"
|
|
45
|
+
for e in result.entities
|
|
46
|
+
]
|
|
47
|
+
return f"[paisa_parse: {'; '.join(parts)}]"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def apply_pipecat_mode(text: str, result: ParseResult, mode: PipecatMode) -> str:
|
|
51
|
+
"""Transform `text` according to the selected Pipecat processor mode."""
|
|
52
|
+
if not result.entities or mode == "callback_only":
|
|
53
|
+
return text
|
|
54
|
+
if mode == "replace":
|
|
55
|
+
return result.normalized_text
|
|
56
|
+
if mode == "annotate":
|
|
57
|
+
tag = format_annotation(result)
|
|
58
|
+
return f"{text} {tag}".strip() if tag else text
|
|
59
|
+
raise ValueError(f"Unsupported mode: {mode!r}. Expected 'annotate', 'replace', or 'callback_only'.")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class PaisaParseProcessor(FrameProcessor):
|
|
63
|
+
"""Pipecat FrameProcessor that enriches TranscriptionFrames with parsed financial entities."""
|
|
64
|
+
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
*,
|
|
68
|
+
policy: ConfirmPolicy | None = None,
|
|
69
|
+
kinds: Iterable[EntityType | str] | None = None,
|
|
70
|
+
mode: PipecatMode = "annotate",
|
|
71
|
+
on_parsed: ParsedCallback | None = None,
|
|
72
|
+
**kwargs: Any,
|
|
73
|
+
) -> None:
|
|
74
|
+
if not _HAS_PIPECAT:
|
|
75
|
+
raise ImportError(
|
|
76
|
+
"Pipecat is not installed. Install with: pip install 'paisa-parse[pipecat]'"
|
|
77
|
+
)
|
|
78
|
+
super().__init__(**kwargs)
|
|
79
|
+
self.policy = policy if policy is not None else ConfirmPolicy.balanced()
|
|
80
|
+
self.kinds = tuple(kinds) if kinds is not None else None
|
|
81
|
+
self.mode: PipecatMode = mode
|
|
82
|
+
self.on_parsed = on_parsed
|
|
83
|
+
self.last_result: ParseResult | None = None
|
|
84
|
+
|
|
85
|
+
async def process_frame(self, frame: Frame, direction: FrameDirection) -> None:
|
|
86
|
+
await super().process_frame(frame, direction)
|
|
87
|
+
|
|
88
|
+
if TranscriptionFrame is not None and isinstance(frame, TranscriptionFrame):
|
|
89
|
+
raw_text = getattr(frame, "text", "") or ""
|
|
90
|
+
result = parse(raw_text, policy=self.policy, kinds=self.kinds)
|
|
91
|
+
self.last_result = result
|
|
92
|
+
|
|
93
|
+
if result.entities:
|
|
94
|
+
frame.text = apply_pipecat_mode(raw_text, result, self.mode)
|
|
95
|
+
|
|
96
|
+
if self.on_parsed is not None:
|
|
97
|
+
maybe_coro = self.on_parsed(result, frame)
|
|
98
|
+
if inspect.isawaitable(maybe_coro):
|
|
99
|
+
await maybe_coro
|
|
100
|
+
|
|
101
|
+
await self.push_frame(frame, direction)
|