File size: 3,795 Bytes
2563c17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Shelly AI - Memory Encoding

Converts events and experiences into structured memory records.
"""

from __future__ import annotations

import re
import time
import uuid

from typing import Any, Dict, Optional


class MemoryEncoder:
    def __init__(self):
        self.encoded_count = 0

    @staticmethod
    def extract_entities(text: str) -> list:
        """
        Extract simple named entities and important terms.

        This is a lightweight heuristic, not a trained NER model.
        """

        if not isinstance(text, str):
            return []

        words = re.findall(
            r"\b[A-Z][a-zA-Z0-9_-]{2,}\b",
            text,
        )

        unique = []

        for word in words:
            if word not in unique:
                unique.append(word)

        return unique[:100]

    @staticmethod
    def extract_keywords(text: str) -> list:
        if not isinstance(text, str):
            return []

        words = re.findall(
            r"[A-Za-z0-9_'-]+",
            text.lower(),
        )

        stop_words = {
            "the", "and", "for", "that", "this", "with",
            "from", "have", "has", "are", "was", "were",
            "you", "your", "she", "her", "they", "them",
            "yang", "dan", "atau", "untuk", "dari", "ini",
            "itu", "aku", "saya", "kamu", "dia", "adalah",
        }

        counts = {}

        for word in words:
            if len(word) > 2 and word not in stop_words:
                counts[word] = counts.get(word, 0) + 1

        ranked = sorted(
            counts.items(),
            key=lambda item: item[1],
            reverse=True,
        )

        return [word for word, _ in ranked[:30]]

    def encode(
        self,
        event: Any,
        context: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        context = dict(context or {})

        if isinstance(event, dict):
            content = event.get(
                "content",
                event.get("event", str(event)),
            )

            event_type = event.get(
                "type",
                event.get("event_type", "experience"),
            )

            source = event.get("source", "conversation")
            user_id = event.get("user_id")
            emotion_state = event.get("emotions", {})
        else:
            content = str(event)
            event_type = "experience"
            source = "conversation"
            user_id = None
            emotion_state = {}

        content = str(content)

        record = {
            "id": str(uuid.uuid4()),
            "event": content,
            "event_type": event_type,
            "timestamp": time.time(),
            "context": context,
            "entities": self.extract_entities(content),
            "keywords": self.extract_keywords(content),
            "topic": context.get("topic"),
            "emotion_state": dict(emotion_state or {}),
            "novelty": float(context.get("novelty", 0.5)),
            "attention": float(context.get("attention", 0.5)),
            "repetitions": 1,
            "confidence": float(context.get("confidence", 0.5)),
            "source": source,
            "user_id": user_id,
            "retrieval_count": 0,
            "importance": float(context.get("importance", 0.5)),
            "original_event": content,
            "interpretations": [],
            "archived": False,
        }

        record["novelty"] = max(
            0.0,
            min(1.0, record["novelty"]),
        )

        record["attention"] = max(
            0.0,
            min(1.0, record["attention"]),
        )

        record["confidence"] = max(
            0.0,
            min(1.0, record["confidence"]),
        )

        self.encoded_count += 1

        return record