File size: 13,155 Bytes
abecf61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#!/usr/bin/env python3
"""
Paninian Parser - Tier 2 of Vedic AI
Based on Ashtadhyayi's Karaka theory for unambiguous command parsing.
100% deterministic - no hallucinations possible.
"""

import re
from dataclasses import dataclass
from typing import Optional, Dict, List
from enum import Enum

# ============================================================
# 1. KARAKA ROLES (Panini's Semantic Roles)
# ============================================================
class Karaka(Enum):
    KARTR = "kartr"           # Agent/Doer (nominative)
    KARMAN = "karman"         # Patient/Object (accusative)
    KARANA = "karana"         # Instrument (instrumental)
    SAMPRAADANA = "sampraadana"  # Recipient (dative)
    APAADANA = "apaadana"     # Source (ablative)
    ADHIKARANA = "adhikarana" # Location (locative)

@dataclass
class ParsedCommand:
    """A perfectly parsed command with zero ambiguity"""
    action: str
    kartr: str                    # Who does it
    karman: Optional[str] = None  # What is acted upon
    karana: Optional[str] = None  # Using what instrument
    adhikarana: Optional[str] = None  # Where
    target_state: Optional[str] = None  # To what state
    condition: Optional[Dict] = None    # If conditional
    
    def to_executable(self) -> Dict:
        """Convert to a deterministic executable form"""
        return {
            "function": self.action,
            "params": {
                "agent": self.kartr,
                "patient": self.karman,
                "instrument": self.karana,
                "location": self.adhikarana,
                "target": self.target_state
            },
            "condition": self.condition
        }

# ============================================================
# 2. FORMAL LEXICON (Perfectly Defined Words)
# ============================================================
ACTIONS = {
    "set", "get", "start", "stop", "toggle", "increase", "decrease",
    "open", "close", "lock", "unlock", "activate", "deactivate"
}

DEVICES = {
    "light", "heater", "fan", "door", "window", "speaker", 
    "thermostat", "camera", "alarm", "lock", "display"
}

LOCATIONS = {
    "living-room", "kitchen", "bedroom", "bathroom", "hall",
    "garage", "office", "outside", "all"
}

STATES = {"on", "off", "locked", "unlocked", "open", "closed"}

COMPARATORS = {
    "less-than": "<", "greater-than": ">", "equals": "==",
    "below": "<", "above": ">", "not-equal": "!="
}

# ============================================================
# 3. PANINIAN PARSER ENGINE
# ============================================================
class PaninianParser:
    """
    Implements a rule-based parser inspired by Panini's Ashtadhyayi.
    Every sentence is decomposed into Karaka roles.
    """
    
    def __init__(self):
        self.rules_applied = []  # Trace of all rules used (for explainability)
    
    def parse(self, command: str) -> ParsedCommand:
        """Main parse function - no ML, no probability, just rules"""
        self.rules_applied = []
        command = command.lower().strip()
        
        # Rule 1: Identify Agent (Kartr) - The invoker or specified doer
        kartr = self._extract_kartr(command)
        
        # Rule 2: Check for conditional
        condition = self._extract_condition(command)
        
        # Rule 3: Extract action (verb)
        action = self._extract_action(command)
        
        # Rule 4: Extract patient (Karman) - What is acted upon
        karman = self._extract_karman(command)
        
        # Rule 5: Extract location (Adhikarana)
        adhikarana = self._extract_adhikarana(command)
        
        # Rule 6: Extract instrument (Karana)
        karana = self._extract_karana(command)
        
        # Rule 7: Extract target state
        target_state = self._extract_target_state(command, action)
        
        return ParsedCommand(
            action=action or "unknown",
            kartr=kartr,
            karman=karman,
            karana=karana,
            adhikarana=adhikarana,
            target_state=target_state,
            condition=condition
        )
    
    def _extract_kartr(self, cmd: str) -> str:
        """Rule: Agent is before comma or 'computer'/'system'"""
        if cmd.startswith("computer"):
            self.rules_applied.append("Kartr: Explicit invocation 'computer'")
            return "computer"
        if "," in cmd:
            before_comma = cmd.split(",")[0].strip()
            if before_comma in ["computer", "system", "phone"]:
                self.rules_applied.append(f"Kartr: Pre-comma designator '{before_comma}'")
                return before_comma
        self.rules_applied.append("Kartr: Default 'system'")
        return "system"
    
    def _extract_condition(self, cmd: str) -> Optional[Dict]:
        """Rule: 'if' clause creates a conditional"""
        if_match = re.search(r'if\s+(\S+)\s+(less-than|greater-than|equals|below|above)\s+(\d+)', cmd)
        if if_match:
            self.rules_applied.append("Condition: If-clause detected")
            return {
                "variable": if_match.group(1),
                "comparator": COMPARATORS.get(if_match.group(2), "=="),
                "value": int(if_match.group(3))
            }
        return None
    
    def _extract_action(self, cmd: str) -> Optional[str]:
        """Rule: Action is one of the defined verbs"""
        # Remove 'if' clause for cleaner parsing
        clean_cmd = re.sub(r'if\s+.*?\d+', '', cmd)
        
        for action in ACTIONS:
            if action in clean_cmd.split():
                self.rules_applied.append(f"Action: Found verb '{action}'")
                return action
        return None
    
    def _extract_karman(self, cmd: str) -> Optional[str]:
        """Rule: Karman follows the action verb with 'the' or directly"""
        for device in DEVICES:
            # Pattern: action + "the" + device OR action + device
            if f"the {device}" in cmd or re.search(rf'\b{re.escape(device)}\b', cmd):
                self.rules_applied.append(f"Karman: Found device '{device}'")
                return device
        return None
    
    def _extract_adhikarana(self, cmd: str) -> Optional[str]:
        """Rule: Location follows 'in' or 'at'"""
        for loc in LOCATIONS:
            if f"in {loc}" in cmd or f"at {loc}" in cmd:
                self.rules_applied.append(f"Adhikarana: Location '{loc}'")
                return loc
        return None
    
    def _extract_karana(self, cmd: str) -> Optional[str]:
        """Rule: Instrument follows 'using' or 'with'"""
        match = re.search(r'(?:using|with)\s+(\w+(?:-\w+)?)', cmd)
        if match:
            self.rules_applied.append(f"Karana: Instrument '{match.group(1)}'")
            return match.group(1)
        return None
    
    def _extract_target_state(self, cmd: str, action: str) -> Optional[str]:
        """Rule: Target state follows 'to' for set-like actions"""
        if action in ["set", "toggle"]:
            for state in STATES:
                if f"to {state}" in cmd:
                    self.rules_applied.append(f"Target: State '{state}'")
                    return state
        return None

# ============================================================
# 4. NYAYA LOGIC AUDITOR (Formal Verification)
# ============================================================
class NyayaAuditor:
    """
    Formal safety auditor using Nyaya-style inference.
    Ensures no command creates an unsafe state.
    """
    
    # Safety rules as formal propositions
    SAFETY_RULES = [
        {
            "rule": "Heater must not be on when window is open",
            "condition": {"patient": "heater", "target": "on"},
            "check": {"patient": "window", "state": "open"},
            "violation": "Cannot turn heater on while window is open"
        },
        {
            "rule": "Door must not be locked when inside is occupied",
            "condition": {"patient": "door", "target": "locked"},
            "check": {"location": "inside", "state": "occupied"},
            "violation": "Cannot lock door while room is occupied"
        }
    ]
    
    def __init__(self):
        # Simulated system state (in real system, this reads actual sensors)
        self.current_state = {
            "window": "closed",
            "heater": "off",
            "door": "unlocked",
            "inside": "unoccupied",
            "temperature": 22
        }
    
    def audit(self, parsed: ParsedCommand) -> tuple[bool, str, str]:
        """
        Returns (is_safe, proof, message)
        Uses formal syllogistic reasoning
        """
        executable = parsed.to_executable()
        
        for rule in self.SAFETY_RULES:
            cond = rule["condition"]
            check = rule["check"]
            
            # Check if command triggers the rule condition
            if (executable["params"]["patient"] == cond["patient"] and 
                executable["params"]["target"] == cond["target"]):
                
                # Now check the safety condition
                state_check = check["patient"]
                required_state = check["state"]
                actual_state = self.current_state.get(state_check, "unknown")
                
                if actual_state == required_state:
                    # Formal syllogism
                    proof = (
                        f"1. Pratijna: The command to set {cond['patient']} to {cond['target']} is unsafe.\n"
                        f"2. Hetu: Because {state_check} is {actual_state}.\n"
                        f"3. Udaharana: The rule states '{rule['rule']}'.\n"
                        f"4. Upanaya: Current {state_check} state is {actual_state}.\n"
                        f"5. Nigamana: Therefore, command violates safety rule."
                    )
                    return False, proof, rule["violation"]
        
        # Safe
        proof = (
            f"1. Pratijna: Command '{parsed.action} {parsed.karman}' is safe.\n"
            f"2. Hetu: No safety rule is violated.\n"
            f"3. Udaharana: All applicable rules checked.\n"
            f"4. Upanaya: Current state does not conflict.\n"
            f"5. Nigamana: Therefore, command is safe to execute."
        )
        return True, proof, "Command is safe"

# ============================================================
# 5. DEMO & TEST SUITE
# ============================================================
def test_parser():
    parser = PaninianParser()
    auditor = NyayaAuditor()
    
    test_commands = [
        "computer, set the heater to on in living-room",
        "if temperature less-than 20, set the heater to on",
        "set the light to off in kitchen",
        "start the fan using speaker",
        "computer, open the door",
        "lock the door in bedroom",
        "get temperature in living-room",
        "toggle the light in hall",
    ]
    
    print("╔══════════════════════════════════════════════════════╗")
    print("β•‘     PANINIAN PARSER - TIER 2 VEDIC AI SHELL        β•‘")
    print("β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•\n")
    
    for i, cmd in enumerate(test_commands, 1):
        print(f"━━━ Test {i} ━━━")
        print(f"Input: \"{cmd}\"")
        parsed = parser.parse(cmd)
        
        print(f"\nπŸ“‹ Parse Result:")
        print(f"  Kartr (Agent):      {parsed.kartr}")
        print(f"  Karman (Patient):   {parsed.karman}")
        print(f"  Action (Verb):      {parsed.action}")
        print(f"  Adhikarana (Loc):   {parsed.adhikarana}")
        print(f"  Karana (Instr):     {parsed.karana}")
        print(f"  Target State:       {parsed.target_state}")
        
        if parsed.condition:
            print(f"  Condition:          IF {parsed.condition['variable']} "
                  f"{parsed.condition['comparator']} {parsed.condition['value']}")
        
        print(f"\nπŸ“ Rules Applied:")
        for rule in parser.rules_applied:
            print(f"  β†’ {rule}")
        
        executable = parsed.to_executable()
        print(f"\nβš™οΈ  Executable Form:")
        print(f"  {executable}")
        
        # Safety audit
        is_safe, proof, msg = auditor.audit(parsed)
        print(f"\nπŸ›‘οΈ  Safety Audit: {'βœ… SAFE' if is_safe else '❌ UNSAFE'}")
        print(f"  {msg}")
        print(f"  Proof:\n{proof}")
        print()
    
    print("╔══════════════════════════════════════════════════════╗")
    print("β•‘     ALL PANINIAN PARSER TESTS COMPLETE βœ“            β•‘")
    print("β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•")

if __name__ == "__main__":
    test_parser()