ripple-down-rules 0.1.3__py3-none-any.whl → 0.1.5__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.
@@ -1,14 +1,18 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import re
3
4
  from abc import ABC, abstractmethod
4
5
  from enum import Enum
5
6
 
6
7
  from anytree import NodeMixin
7
8
  from typing_extensions import List, Optional, Self, Union, Dict, Any
8
9
 
9
- from .datastructures import CallableExpression, Case, SQLTable
10
+ from .datastructures.callable_expression import CallableExpression
11
+ from .datastructures.case import Case
12
+ from sqlalchemy.orm import DeclarativeBase as SQLTable
10
13
  from .datastructures.enums import RDREdge, Stop
11
- from .utils import SubclassJSONSerializer, is_iterable, get_full_class_name
14
+ from .utils import SubclassJSONSerializer, is_iterable, get_full_class_name, conclusion_to_json, \
15
+ get_rule_conclusion_as_source_code
12
16
 
13
17
 
14
18
  class Rule(NodeMixin, SubclassJSONSerializer, ABC):
@@ -41,6 +45,7 @@ class Rule(NodeMixin, SubclassJSONSerializer, ABC):
41
45
  self.conditions = conditions if conditions else None
42
46
  self.conclusion_name: Optional[str] = conclusion_name
43
47
  self.json_serialization: Optional[Dict[str, Any]] = None
48
+ self._name: Optional[str] = None
44
49
 
45
50
  def _post_detach(self, parent):
46
51
  """
@@ -79,43 +84,48 @@ class Rule(NodeMixin, SubclassJSONSerializer, ABC):
79
84
 
80
85
  :param parent_indent: The indentation of the parent rule.
81
86
  """
82
- if isinstance(self.conclusion, CallableExpression):
83
- conclusion = self.conclusion.parsed_user_input
84
- elif isinstance(self.conclusion, Enum):
85
- conclusion = str(self.conclusion)
86
- else:
87
- conclusion = self.conclusion
88
- return self._conclusion_source_code_clause(conclusion, parent_indent=parent_indent)
87
+ conclusion = self.conclusion
88
+ if isinstance(conclusion, CallableExpression):
89
+ if self.conclusion.user_input is not None:
90
+ conclusion = self.conclusion.user_input
91
+ else:
92
+ conclusion = self.conclusion.conclusion
93
+ if isinstance(conclusion, Enum):
94
+ conclusion = str(conclusion)
95
+ return self._conclusion_source_code(conclusion, parent_indent=parent_indent)
89
96
 
90
97
  @abstractmethod
91
- def _conclusion_source_code_clause(self, conclusion: Any, parent_indent: str = "") -> str:
98
+ def _conclusion_source_code(self, conclusion: Any, parent_indent: str = "") -> str:
92
99
  pass
93
100
 
94
- def write_condition_as_source_code(self, parent_indent: str = "") -> str:
101
+ def write_condition_as_source_code(self, parent_indent: str = "", defs_file: Optional[str] = None) -> str:
95
102
  """
96
103
  Get the source code representation of the conditions of the rule.
97
104
 
98
105
  :param parent_indent: The indentation of the parent rule.
106
+ :param defs_file: The file to write the conditions to if they are a definition.
99
107
  """
100
108
  if_clause = self._if_statement_source_code_clause()
101
- return f"{parent_indent}{if_clause} {self.conditions.parsed_user_input}:\n"
109
+ if '\n' not in self.conditions.user_input:
110
+ return f"{parent_indent}{if_clause} {self.conditions.user_input}:\n"
111
+ elif "def " in self.conditions.user_input:
112
+ if defs_file is None:
113
+ raise ValueError("Cannot write conditions to source code as definitions python file was not given.")
114
+ # This means the conditions are a definition that should be written and then called
115
+ conditions_lines = self.conditions.user_input.split('\n')
116
+ # use regex to replace the function name
117
+ new_function_name = f"def conditions_{id(self)}"
118
+ conditions_lines[0] = re.sub(r"def (\w+)", new_function_name, conditions_lines[0])
119
+ def_code = "\n".join(conditions_lines)
120
+ with open(defs_file, 'a') as f:
121
+ f.write(def_code + "\n")
122
+ return f"\n{parent_indent}{if_clause} {new_function_name.replace('def ', '')}(case):\n"
102
123
 
103
124
  @abstractmethod
104
125
  def _if_statement_source_code_clause(self) -> str:
105
126
  pass
106
127
 
107
128
  def _to_json(self) -> Dict[str, Any]:
108
- def conclusion_to_json(conclusion):
109
- if is_iterable(conclusion):
110
- conclusions = {'_type': get_full_class_name(type(conclusion)), 'value': []}
111
- for c in conclusion:
112
- conclusions['value'].append(conclusion_to_json(c))
113
- elif hasattr(conclusion, 'to_json'):
114
- conclusions = conclusion.to_json()
115
- else:
116
- conclusions = {'_type': get_full_class_name(type(conclusion)), 'value': conclusion}
117
- return conclusions
118
-
119
129
  json_serialization = {"conditions": self.conditions.to_json(),
120
130
  "conclusion": conclusion_to_json(self.conclusion),
121
131
  "parent": self.parent.json_serialization if self.parent else None,
@@ -137,7 +147,14 @@ class Rule(NodeMixin, SubclassJSONSerializer, ABC):
137
147
  """
138
148
  Get the name of the rule, which is the conditions and the conclusion.
139
149
  """
140
- return self.__str__()
150
+ return self._name if self._name is not None else self.__str__()
151
+
152
+ @name.setter
153
+ def name(self, new_name: str):
154
+ """
155
+ Set the name of the rule.
156
+ """
157
+ self._name = new_name
141
158
 
142
159
  def __str__(self, sep="\n"):
143
160
  """
@@ -247,8 +264,13 @@ class SingleClassRule(Rule, HasAlternativeRule, HasRefinementRule):
247
264
  loaded_rule.alternative = SingleClassRule.from_json(data["alternative"])
248
265
  return loaded_rule
249
266
 
250
- def _conclusion_source_code_clause(self, conclusion: Any, parent_indent: str = "") -> str:
251
- return f"{parent_indent}{' ' * 4}return {conclusion}\n"
267
+ def _conclusion_source_code(self, conclusion: Any, parent_indent: str = "") -> str:
268
+ conclusion = str(conclusion)
269
+ indent = parent_indent + " " * 4
270
+ if '\n' not in conclusion:
271
+ return f"{indent}return {conclusion}\n"
272
+ else:
273
+ return get_rule_conclusion_as_source_code(self, conclusion, parent_indent=parent_indent)
252
274
 
253
275
  def _if_statement_source_code_clause(self) -> str:
254
276
  return "elif" if self.weight == RDREdge.Alternative.value else "if"
@@ -293,7 +315,7 @@ class MultiClassStopRule(Rule, HasAlternativeRule):
293
315
  loaded_rule.alternative = MultiClassStopRule.from_json(data["alternative"])
294
316
  return loaded_rule
295
317
 
296
- def _conclusion_source_code_clause(self, conclusion: Any, parent_indent: str = "") -> str:
318
+ def _conclusion_source_code(self, conclusion: Any, parent_indent: str = "") -> str:
297
319
  return f"{parent_indent}{' ' * 4}pass\n"
298
320
 
299
321
  def _if_statement_source_code_clause(self) -> str:
@@ -338,12 +360,22 @@ class MultiClassTopRule(Rule, HasRefinementRule, HasAlternativeRule):
338
360
  loaded_rule.alternative = MultiClassTopRule.from_json(data["alternative"])
339
361
  return loaded_rule
340
362
 
341
- def _conclusion_source_code_clause(self, conclusion: Any, parent_indent: str = "") -> str:
342
- if is_iterable(conclusion):
343
- conclusion_str = "{" + ", ".join([str(c) for c in conclusion]) + "}"
363
+ def _conclusion_source_code(self, conclusion: Any, parent_indent: str = "") -> str:
364
+ conclusion_str = str(conclusion)
365
+ indent = parent_indent + " " * 4
366
+ statement = ""
367
+ if '\n' not in conclusion_str:
368
+ if is_iterable(conclusion):
369
+ conclusion_str = "{" + ", ".join([str(c) for c in conclusion]) + "}"
370
+ else:
371
+ conclusion_str = "{" + str(conclusion) + "}"
344
372
  else:
345
- conclusion_str = "{" + str(conclusion) + "}"
346
- statement = f"{parent_indent}{' ' * 4}conclusions.update({conclusion_str})\n"
373
+ conclusion_str = get_rule_conclusion_as_source_code(self, conclusion_str, parent_indent=parent_indent)
374
+ lines = conclusion_str.split("\n")
375
+ conclusion_str = lines[-2].replace("return ", "").strip()
376
+ statement += "\n".join(lines[:-2]) + "\n"
377
+
378
+ statement += f"{indent}conclusions.update(make_set({conclusion_str}))\n"
347
379
  if self.alternative is None:
348
380
  statement += f"{parent_indent}return conclusions\n"
349
381
  return statement
@@ -1,16 +1,20 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import ast
4
+ import builtins
4
5
  import importlib
5
6
  import json
6
7
  import logging
7
8
  import os
9
+ import re
8
10
  from collections import UserDict
9
11
  from copy import deepcopy
10
12
  from dataclasses import is_dataclass, fields
13
+ from types import NoneType
11
14
 
12
15
  import matplotlib
13
16
  import networkx as nx
17
+ import requests
14
18
  from anytree import Node, RenderTree
15
19
  from anytree.exporter import DotExporter
16
20
  from matplotlib import pyplot as plt
@@ -21,13 +25,93 @@ from typing_extensions import Callable, Set, Any, Type, Dict, TYPE_CHECKING, get
21
25
  get_origin, get_args, Tuple, Optional, List, Union, Self
22
26
 
23
27
  if TYPE_CHECKING:
24
- from .datastructures import Case
28
+ from .datastructures.case import Case
29
+ from .rules import Rule
25
30
 
26
31
  import ast
27
32
 
28
33
  matplotlib.use("Qt5Agg") # or "Qt5Agg", depending on availability
29
34
 
30
35
 
36
+ def get_rule_conclusion_as_source_code(rule: Rule, conclusion: str, parent_indent: str = "") -> str:
37
+ """
38
+ Convert the conclusion of a rule to source code.
39
+
40
+ :param rule: The rule to get the conclusion from.
41
+ :param conclusion: The conclusion to convert to source code.
42
+ :param parent_indent: The indentation to use for the source code.
43
+ :return: The source code of the conclusion.
44
+ """
45
+ indent = f"{parent_indent}{' ' * 4}"
46
+ if "def " in conclusion:
47
+ # This means the conclusion is a definition that should be written and then called
48
+ conclusion_lines = conclusion.split('\n')
49
+ # use regex to replace the function name
50
+ new_function_name = f"def conclusion_{id(rule)}"
51
+ conclusion_lines[0] = re.sub(r"def (\w+)", new_function_name, conclusion_lines[0])
52
+ conclusion_lines = [f"{indent}{line}" for line in conclusion_lines]
53
+ conclusion_lines.append(f"{indent}return {new_function_name.replace('def ', '')}(case)\n")
54
+ return "\n".join(conclusion_lines)
55
+ else:
56
+ raise ValueError(f"Conclusion is format is not valid, it should be a one line string or "
57
+ f"contain a function definition. Instead got:\n{conclusion}\n")
58
+
59
+
60
+ def ask_llm(prompt):
61
+ try:
62
+ response = requests.post("http://localhost:11434/api/generate", json={
63
+ "model": "codellama:7b-instruct", # or "phi"
64
+ "prompt": prompt,
65
+ "stream": False,
66
+ })
67
+ result = response.json()
68
+ return result.get("response", "").strip()
69
+ except Exception as e:
70
+ return f"❌ Local LLM error: {e}"
71
+
72
+
73
+ def get_case_attribute_type(original_case: Any, attribute_name: str,
74
+ known_value: Optional[Any] = None) -> Type:
75
+ """
76
+ :param original_case: The case to get the attribute from.
77
+ :param attribute_name: The name of the attribute.
78
+ :param known_value: A known value of the attribute.
79
+ :return: The type of the attribute.
80
+ """
81
+ if known_value is not None:
82
+ return type(known_value)
83
+ elif hasattr(original_case, attribute_name):
84
+ hint, origin, args = get_hint_for_attribute(attribute_name, original_case)
85
+ if origin is not None:
86
+ origin = typing_to_python_type(origin)
87
+ if origin == Union:
88
+ if len(args) == 2:
89
+ if args[1] is type(None):
90
+ return typing_to_python_type(args[0])
91
+ elif args[0] is type(None):
92
+ return typing_to_python_type(args[1])
93
+ elif len(args) == 1:
94
+ return typing_to_python_type(args[0])
95
+ else:
96
+ raise ValueError(f"Union with more than 2 types is not supported: {args}")
97
+ elif origin is not None:
98
+ return origin
99
+ if hint is not None:
100
+ return typing_to_python_type(hint)
101
+
102
+
103
+ def conclusion_to_json(conclusion):
104
+ if is_iterable(conclusion):
105
+ conclusions = {'_type': get_full_class_name(type(conclusion)), 'value': []}
106
+ for c in conclusion:
107
+ conclusions['value'].append(conclusion_to_json(c))
108
+ elif hasattr(conclusion, 'to_json'):
109
+ conclusions = conclusion.to_json()
110
+ else:
111
+ conclusions = {'_type': get_full_class_name(type(conclusion)), 'value': conclusion}
112
+ return conclusions
113
+
114
+
31
115
  def contains_return_statement(source: str) -> bool:
32
116
  """
33
117
  :param source: The source code to check.
@@ -292,6 +376,8 @@ def get_type_from_string(type_path: str):
292
376
  """
293
377
  module_path, class_name = type_path.rsplit(".", 1)
294
378
  module = importlib.import_module(module_path)
379
+ if module == builtins and class_name == 'NoneType':
380
+ return type(None)
295
381
  return getattr(module, class_name)
296
382
 
297
383
 
@@ -389,6 +475,8 @@ class SubclassJSONSerializer:
389
475
  data_type = get_type_from_string(data["_type"])
390
476
  if len(data) == 1:
391
477
  return data_type
478
+ if data_type == NoneType:
479
+ return None
392
480
  if data_type.__module__ == 'builtins':
393
481
  if is_iterable(data['value']) and not isinstance(data['value'], dict):
394
482
  return data_type([cls.from_json(d) for d in data['value']])
@@ -516,6 +604,7 @@ def table_rows_as_str(row_dict: Dict[str, Any], columns_per_row: int = 9):
516
604
  values = [list(map(lambda i: i[1], row)) for row in all_items]
517
605
  all_table_rows = []
518
606
  for row_keys, row_values in zip(keys, values):
607
+ row_values = [str(v) if v is not None else "" for v in row_values]
519
608
  table = tabulate([row_values], headers=row_keys, tablefmt='plain', maxcolwidths=[20] * len(row_keys))
520
609
  all_table_rows.append(table)
521
610
  return "\n".join(all_table_rows)
@@ -652,7 +741,7 @@ def get_all_subclasses(cls: Type) -> Dict[str, Type]:
652
741
  return all_subclasses
653
742
 
654
743
 
655
- def make_set(value: Any) -> Set:
744
+ def make_set(value: Any) -> Set[Any]:
656
745
  """
657
746
  Make a set from a value.
658
747
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ripple_down_rules
3
- Version: 0.1.3
3
+ Version: 0.1.5
4
4
  Summary: Implements the various versions of Ripple Down Rules (RDR) for knowledge representation and reasoning.
5
5
  Author-email: Abdelrhman Bassiouny <abassiou@uni-bremen.de>
6
6
  License: GNU GENERAL PUBLIC LICENSE
@@ -0,0 +1,20 @@
1
+ ripple_down_rules/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ ripple_down_rules/datasets.py,sha256=rCSpeFeu1gTuKESwjHUdQkPPvomI5OMRNGpbdKmHwMg,4639
3
+ ripple_down_rules/experts.py,sha256=sA9Cmx9BlwlCFYRDDLz3VG6e5njujAFZEItSnnzrG5E,10490
4
+ ripple_down_rules/failures.py,sha256=E6ajDUsw3Blom8eVLbA7d_Qnov2conhtZ0UmpQ9ZtSE,302
5
+ ripple_down_rules/helpers.py,sha256=AhqerAQoCdSovJ7SdQrNtAI_hYagKpLsy2nJQGA0bl0,1062
6
+ ripple_down_rules/prompt.py,sha256=6g-WqMiOFp9QyAZDmiNbHbPjAeeJHb6ItLGdQAVxGKk,6063
7
+ ripple_down_rules/rdr.py,sha256=HevACyk22k2m7sTKDTxbFiRp4MOQNK7XSOvJyVBg20Q,50047
8
+ ripple_down_rules/rdr_decorators.py,sha256=8SclpceI3EtrsbuukWJu8HGLh7Q1ZCgYGLX-RPlG-w0,2018
9
+ ripple_down_rules/rules.py,sha256=KTB7kPnyyU9GuZhVe9ba25-3ICdzl46r9MFduckk-_Y,16147
10
+ ripple_down_rules/utils.py,sha256=0yyLpvt-GEamV4Z3515ip200IfzpqOhNcrXhGzZtEPk,30521
11
+ ripple_down_rules/datastructures/__init__.py,sha256=V2aNgf5C96Y5-IGghra3n9uiefpoIm_QdT7cc_C8cxQ,111
12
+ ripple_down_rules/datastructures/callable_expression.py,sha256=TW_u6CJfelW2CiJj9pWFpdOBNIxeEuhhsQEz_pLpFVE,9092
13
+ ripple_down_rules/datastructures/case.py,sha256=A7qkl5W48zldTtA4m-NJRYEwlMBpo7uGugnriNwcY0E,13597
14
+ ripple_down_rules/datastructures/dataclasses.py,sha256=2HISRjO_rfsOVCD19bmWkR5tRK9kWyFGTn3QHdMfLSw,5829
15
+ ripple_down_rules/datastructures/enums.py,sha256=l0Eu-TeJ6qB2XHoJycXmUgLw-3yUebQ8SsEbW8bBZdM,4543
16
+ ripple_down_rules-0.1.5.dist-info/licenses/LICENSE,sha256=ixuiBLtpoK3iv89l7ylKkg9rs2GzF9ukPH7ynZYzK5s,35148
17
+ ripple_down_rules-0.1.5.dist-info/METADATA,sha256=zjPgcX0Z3DMcPnU5YjbVRPu8w2MhdQ4gimpdC9JabJk,42518
18
+ ripple_down_rules-0.1.5.dist-info/WHEEL,sha256=ck4Vq1_RXyvS4Jt6SI0Vz6fyVs4GWg7AINwpsaGEgPE,91
19
+ ripple_down_rules-0.1.5.dist-info/top_level.txt,sha256=VeoLhEhyK46M1OHwoPbCQLI1EifLjChqGzhQ6WEUqeM,18
20
+ ripple_down_rules-0.1.5.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (79.0.1)
2
+ Generator: setuptools (80.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,20 +0,0 @@
1
- ripple_down_rules/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- ripple_down_rules/datasets.py,sha256=AzPtqUXuR1qLQNtRsWLsJ3gX2oIf8nIkFvmsmz7fHlw,4601
3
- ripple_down_rules/experts.py,sha256=Xz1U1Tdq7jrFlcVuSusaMB241AG9TEs7q101i59Xijs,10683
4
- ripple_down_rules/failures.py,sha256=E6ajDUsw3Blom8eVLbA7d_Qnov2conhtZ0UmpQ9ZtSE,302
5
- ripple_down_rules/helpers.py,sha256=AhqerAQoCdSovJ7SdQrNtAI_hYagKpLsy2nJQGA0bl0,1062
6
- ripple_down_rules/prompt.py,sha256=kXQAiNDCayB6Ijecxx487eOqqWLcfvmp0q7FbyfuQM0,6433
7
- ripple_down_rules/rdr.py,sha256=NXVYIflUxcDzC5DDrK-l_ZT-sBmUV1ZgkznshSsJZYc,43508
8
- ripple_down_rules/rdr_decorators.py,sha256=8SclpceI3EtrsbuukWJu8HGLh7Q1ZCgYGLX-RPlG-w0,2018
9
- ripple_down_rules/rules.py,sha256=aM3Im4ePuFDlkuD2EKRtiVmYgoQ_sxlwcbzrDKqXAfs,14578
10
- ripple_down_rules/utils.py,sha256=HWu5rvAaV2SXIORHR0c2RBdWNc9q4B7DjWIskuyDTA8,26877
11
- ripple_down_rules/datastructures/__init__.py,sha256=zpmiYm4WkwNHaGdTIfacS7llN5d2xyU6U-saH_TpydI,103
12
- ripple_down_rules/datastructures/callable_expression.py,sha256=noukQQh1Loto9s8EJWnaS-7kaPaKuUccyEz5xHp7KtI,10790
13
- ripple_down_rules/datastructures/case.py,sha256=3Pl07jmYn94wdCVTaRZDmBPgyAsN1TjebvrE6-68MVU,13606
14
- ripple_down_rules/datastructures/dataclasses.py,sha256=AI-wqNy8y9QPg6lov0P-c5b8JXemuM4X62tIRhW-Gqs,4231
15
- ripple_down_rules/datastructures/enums.py,sha256=l0Eu-TeJ6qB2XHoJycXmUgLw-3yUebQ8SsEbW8bBZdM,4543
16
- ripple_down_rules-0.1.3.dist-info/licenses/LICENSE,sha256=ixuiBLtpoK3iv89l7ylKkg9rs2GzF9ukPH7ynZYzK5s,35148
17
- ripple_down_rules-0.1.3.dist-info/METADATA,sha256=k5i5LEQ0cEKeuTQvwRIBNYy3YAVG160mvh8DYsJKxJ0,42518
18
- ripple_down_rules-0.1.3.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91
19
- ripple_down_rules-0.1.3.dist-info/top_level.txt,sha256=VeoLhEhyK46M1OHwoPbCQLI1EifLjChqGzhQ6WEUqeM,18
20
- ripple_down_rules-0.1.3.dist-info/RECORD,,