SkyWorlds01 commited on
Commit
22d5047
·
verified ·
1 Parent(s): d25bf0a

Create Shelly/habits.py

Browse files
Files changed (1) hide show
  1. Shelly/habits.py +174 -0
Shelly/habits.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shelly AI - Habit System
3
+
4
+ Tracks repeated actions and estimates habit strength.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import threading
10
+ import time
11
+ import uuid
12
+
13
+ from typing import Any, Dict, List, Optional
14
+
15
+
16
+ class HabitSystem:
17
+ def __init__(self):
18
+ self._lock = threading.RLock()
19
+
20
+ self.habits: Dict[str, Dict[str, Any]] = {}
21
+ self.action_history: List[Dict[str, Any]] = []
22
+
23
+ self.maximum_history = 2000
24
+
25
+ def record_action(
26
+ self,
27
+ action: str,
28
+ context: Optional[Dict[str, Any]] = None,
29
+ ) -> Dict[str, Any]:
30
+ action = str(action).strip()
31
+
32
+ if not action:
33
+ raise ValueError("Action cannot be empty.")
34
+
35
+ context = dict(context or {})
36
+ now = time.time()
37
+
38
+ record = {
39
+ "id": str(uuid.uuid4()),
40
+ "action": action,
41
+ "context": context,
42
+ "timestamp": now,
43
+ }
44
+
45
+ with self._lock:
46
+ self.action_history.append(record)
47
+
48
+ if len(self.action_history) > self.maximum_history:
49
+ self.action_history = (
50
+ self.action_history[-self.maximum_history:]
51
+ )
52
+
53
+ habit = self.habits.get(action)
54
+
55
+ if habit is None:
56
+ habit = {
57
+ "action": action,
58
+ "occurrences": 0,
59
+ "strength": 0.0,
60
+ "first_seen": now,
61
+ "last_seen": now,
62
+ "contexts": [],
63
+ }
64
+
65
+ self.habits[action] = habit
66
+
67
+ habit["occurrences"] += 1
68
+ habit["last_seen"] = now
69
+
70
+ habit["strength"] = min(
71
+ 1.0,
72
+ habit["strength"] + 0.05,
73
+ )
74
+
75
+ if context and context not in habit["contexts"]:
76
+ habit["contexts"].append(context)
77
+
78
+ if len(habit["contexts"]) > 20:
79
+ habit["contexts"] = habit["contexts"][-20:]
80
+
81
+ return dict(habit)
82
+
83
+ def identify_repeated_actions(
84
+ self,
85
+ minimum_occurrences: int = 3,
86
+ ) -> List[Dict[str, Any]]:
87
+ minimum_occurrences = max(
88
+ 2,
89
+ int(minimum_occurrences),
90
+ )
91
+
92
+ with self._lock:
93
+ results = [
94
+ dict(habit)
95
+ for habit in self.habits.values()
96
+ if habit["occurrences"] >= minimum_occurrences
97
+ ]
98
+
99
+ results.sort(
100
+ key=lambda item: (
101
+ item["strength"],
102
+ item["occurrences"],
103
+ ),
104
+ reverse=True,
105
+ )
106
+
107
+ return results
108
+
109
+ def reduce_habit_strength(
110
+ self,
111
+ action: str,
112
+ amount: float = 0.05,
113
+ ) -> bool:
114
+ with self._lock:
115
+ habit = self.habits.get(str(action))
116
+
117
+ if habit is None:
118
+ return False
119
+
120
+ habit["strength"] = max(
121
+ 0.0,
122
+ habit["strength"] - max(0.0, float(amount)),
123
+ )
124
+
125
+ return True
126
+
127
+ def remove_habit(self, action: str) -> bool:
128
+ with self._lock:
129
+ return self.habits.pop(
130
+ str(action),
131
+ None,
132
+ ) is not None
133
+
134
+ def get_habit(self, action: str) -> Optional[Dict[str, Any]]:
135
+ with self._lock:
136
+ habit = self.habits.get(str(action))
137
+
138
+ return dict(habit) if habit is not None else None
139
+
140
+ def get_status(self) -> Dict[str, Any]:
141
+ with self._lock:
142
+ return {
143
+ "habit_count": len(self.habits),
144
+ "action_count": len(self.action_history),
145
+ "repeated_habits": len(
146
+ self.identify_repeated_actions()
147
+ ),
148
+ }
149
+
150
+ def export_state(self) -> Dict[str, Any]:
151
+ with self._lock:
152
+ return {
153
+ "habits": {
154
+ key: dict(value)
155
+ for key, value in self.habits.items()
156
+ },
157
+ "action_history": [
158
+ dict(item)
159
+ for item in self.action_history
160
+ ],
161
+ }
162
+
163
+ def import_state(self, state: Dict[str, Any]) -> None:
164
+ with self._lock:
165
+ self.habits = {
166
+ key: dict(value)
167
+ for key, value in state.get("habits", {}).items()
168
+ }
169
+
170
+ self.action_history = [
171
+ dict(item)
172
+ for item in state.get("action_history", [])
173
+ ]
174
+