artecnosomatic commited on
Commit
0919d5b
·
0 Parent(s):

Initial commit: Memory Chat application

Browse files
.gradio/certificate.pem ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN CERTIFICATE-----
2
+ MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
3
+ TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
4
+ cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
5
+ WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
6
+ ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
7
+ MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
8
+ h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
9
+ 0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
10
+ A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
11
+ T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
12
+ B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
13
+ B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
14
+ KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
15
+ OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
16
+ jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
17
+ qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
18
+ rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
19
+ HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
20
+ hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
21
+ ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
22
+ 3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
23
+ NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
24
+ ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
25
+ TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
26
+ jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
27
+ oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
28
+ 4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
29
+ mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
30
+ emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
31
+ -----END CERTIFICATE-----
MANUAL_UPLOAD.md ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Manual Upload to Hugging Face Spaces
2
+
3
+ ## Quick Manual Upload Process
4
+
5
+ ### Step 1: Create Your Space
6
+
7
+ 1. **Go to**: https://huggingface.co/spaces
8
+ 2. **Sign in** to your Hugging Face account
9
+ 3. **Click "Create new Space"** (top right)
10
+ 4. **Set Space Name**: Choose a name (e.g., `your-username/memory-chat`)
11
+ 5. **Select Type**: Choose "Gradio"
12
+ 6. **Set Visibility**: Select "Public"
13
+ 7. **Click "Create Space"**
14
+
15
+ ### Step 2: Upload Files
16
+
17
+ In your new Space:
18
+
19
+ 1. **Click "Files and versions"** tab
20
+ 2. **Click "Upload file"**
21
+ 3. **Upload these files**:
22
+
23
+ | File | Description |
24
+ |------|-------------|
25
+ | `app.py` | Main application |
26
+ | `memory_manager.py` | Memory storage system |
27
+ | `chat_interface.py` | Hugging Face integration |
28
+ | `config.py` | Configuration settings |
29
+ | `requirements.txt` | Python dependencies |
30
+ | `README.md` | Documentation |
31
+
32
+ 4. **For each file**:
33
+ - Click "Upload file"
34
+ - Select the file from your computer
35
+ - Add commit message: "Add [filename]"
36
+ - Click "Commit changes"
37
+
38
+ ### Step 3: Wait for Build
39
+
40
+ 1. **Go to "Logs" tab** to monitor the build
41
+ 2. **Wait 3-5 minutes** for the first build
42
+ 3. **Check for any errors** in the logs
43
+
44
+ ### Step 4: Access Your Space
45
+
46
+ Once built, your Space will be live at:
47
+ ```
48
+ https://huggingface.co/spaces/your-username/memory-chat
49
+ ```
50
+
51
+ ## File Contents Summary
52
+
53
+ ### `app.py` (10KB)
54
+ - Main application optimized for HF Spaces
55
+ - Memory management and chat interface
56
+ - Gradio UI with multiple tabs
57
+
58
+ ### `memory_manager.py` (7.7KB)
59
+ - Vector embeddings for memory storage
60
+ - FAISS indexing for fast retrieval
61
+ - Persistent JSON storage
62
+
63
+ ### `chat_interface.py` (3.8KB)
64
+ - Hugging Face model integration
65
+ - DialoGPT model loading
66
+ - Response generation
67
+
68
+ ### `config.py` (1.2KB)
69
+ - Application configuration
70
+ - Model settings and memory parameters
71
+
72
+ ### `requirements.txt` (238B)
73
+ - Python dependencies for HF Spaces
74
+ - Optimized for Spaces environment
75
+
76
+ ### `README.md` (1.3KB)
77
+ - User documentation
78
+ - Usage instructions
79
+
80
+ ## Troubleshooting
81
+
82
+ ### Build Failures
83
+ - Check "Logs" tab for error messages
84
+ - Ensure all files are uploaded correctly
85
+ - Verify requirements.txt format
86
+
87
+ ### Model Loading Issues
88
+ - First-time loading may be slow (30-60 seconds)
89
+ - Application has fallback modes
90
+ - Check internet connection
91
+
92
+ ### Memory Issues
93
+ - Ensure `app.py` is uploaded (not `space_app.py`)
94
+ - Check file permissions
95
+ - Verify `/tmp/memories` directory access
96
+
97
+ ## Success Indicators
98
+
99
+ ✅ **Build Success**: "Build completed successfully" in logs
100
+ ✅ **App Running**: "App is running on port 7860"
101
+ ✅ **Space Live**: URL accessible and interactive
102
+
103
+ ## After Deployment
104
+
105
+ 1. **Test the chat functionality**
106
+ 2. **Verify memory recording**
107
+ 3. **Share your Space URL**
108
+ 4. **Monitor usage in dashboard**
109
+
110
+ ---
111
+
112
+ **Your Memory Chat application is ready for upload!** 🚀
QUICK_DEPLOY.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚀 SUPER QUICK DEPLOYMENT GUIDE
2
+
3
+ ## One-Click Deployment Process
4
+
5
+ ### Step 1: Create Space (2 minutes)
6
+ Click this link: https://huggingface.co/spaces/new
7
+
8
+ **Fill in these exact details:**
9
+ - **Space name**: `memory-chat` (or any name you like)
10
+ - **Space type**: `Gradio`
11
+ - **Visibility**: `Public`
12
+ - **Click**: "Create Space"
13
+
14
+ ### Step 2: Upload Files (3 minutes)
15
+
16
+ **Click "Upload file" and upload these files in order:**
17
+
18
+ 1. **app.py** → Add commit: "Add main application"
19
+ 2. **memory_manager.py** → Add commit: "Add memory system"
20
+ 3. **chat_interface.py** → Add commit: "Add chat interface"
21
+ 4. **config.py** → Add commit: "Add configuration"
22
+ 5. **requirements.txt** → Add commit: "Add dependencies"
23
+ 6. **README.md** → Add commit: "Add documentation"
24
+
25
+ ### Step 3: Wait & Watch (3-5 minutes)
26
+
27
+ **Go to "Logs" tab and watch the build:**
28
+ - Should say "Build completed successfully"
29
+ - If errors, check file uploads
30
+
31
+ ### Step 4: Enjoy! (Instant)
32
+
33
+ **Your Space URL:**
34
+ ```
35
+ https://huggingface.co/spaces/YOUR_USERNAME/memory-chat
36
+ ```
37
+
38
+ ## 🎯 What You'll Get
39
+
40
+ ✅ **Live AI Chat** with memory recording
41
+ ✅ **Beautiful Interface** with 4 tabs
42
+ ✅ **Persistent Storage** for memories
43
+ ✅ **Multi-user Support** for sharing
44
+
45
+ ## 📱 Direct Links
46
+
47
+ - **Create Space**: https://huggingface.co/spaces/new
48
+ - **Your Spaces**: https://huggingface.co/spaces/YOUR_USERNAME
49
+ - **Space Settings**: Click "Settings" in your Space
50
+
51
+ ## 🆘 If You Get Stuck
52
+
53
+ **Common Issues:**
54
+ 1. **Build fails**: Re-upload files, check "Logs" tab
55
+ 2. **App not loading**: Wait 2 minutes, refresh page
56
+ 3. **Memory not working**: Ensure app.py uploaded (not space_app.py)
57
+
58
+ **Quick Fix Commands:**
59
+ ```bash
60
+ # If build fails, re-upload all files:
61
+ app.py → "Fix main app"
62
+ memory_manager.py → "Fix memory system"
63
+ chat_interface.py → "Fix chat interface"
64
+ config.py → "Fix config"
65
+ requirements.txt → "Fix dependencies"
66
+ README.md → "Fix docs"
67
+ ```
68
+
69
+ ---
70
+
71
+ **Total Time: 10 minutes**
72
+ **Your Space will be LIVE and ready to use!**
73
+
74
+ **Questions?** Just ask and I'll help you through any step! 🚀
README.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Memory Chat
2
+
3
+ A conversational AI application built with Hugging Face models that records and remembers user memories.
4
+
5
+ ## Features
6
+
7
+ - 🤖 Hugging Face model integration
8
+ - 💾 Memory storage and retrieval
9
+ - 💬 Simple conversational interface
10
+ - 🔐 Secure memory management
11
+
12
+ ## Setup
13
+
14
+ 1. Install requirements:
15
+ ```bash
16
+ pip install -r requirements.txt
17
+ ```
18
+
19
+ 2. Set up Hugging Face API token:
20
+ ```bash
21
+ export HUGGINGFACE_API_TOKEN=your_token_here
22
+ ```
23
+
24
+ 3. Run the application:
25
+ ```bash
26
+ python app.py
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ The application provides a simple interface where you can:
32
+ - Have conversations with the AI
33
+ - The AI will automatically record important memories from your conversations
34
+ - Retrieve memories when relevant to the conversation
35
+ - View your memory timeline
36
+
37
+ ## Project Structure
38
+
39
+ ```
40
+ hf-memory-chat/
41
+ ├── app.py # Main application
42
+ ├── memory_manager.py # Memory storage and retrieval
43
+ ├── chat_interface.py # Conversational interface
44
+ ├── config.py # Configuration settings
45
+ ├── requirements.txt # Python dependencies
46
+ └── memories/ # Memory storage directory
47
+ ├── memories.json # Memory database
48
+ └── timeline.md # Human-readable memory timeline
49
+ ```
50
+
51
+ ## License
52
+
53
+ MIT License
README_SPACES.md ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🤖 Memory Chat - Hugging Face Spaces
2
+
3
+ A conversational AI application built with Hugging Face models that records and remembers user memories. Deployed on Hugging Face Spaces with persistent storage.
4
+
5
+ ## 🚀 Features
6
+
7
+ - 🤖 **Hugging Face Integration**: Uses DialoGPT for natural conversations
8
+ - 💾 **Memory System**: Automatically records important information from conversations
9
+ - 📚 **Memory Management**: View, search, and manage your memories
10
+ - 🔍 **Smart Retrieval**: AI recalls relevant memories during conversations
11
+ - ☁️ **Persistent Storage**: Memories persist between sessions on the Space
12
+
13
+ ## 🎯 How It Works
14
+
15
+ 1. **Conversation**: Chat naturally with the AI using Hugging Face models
16
+ 2. **Memory Detection**: The system automatically detects important information using keywords and patterns
17
+ 3. **Memory Storage**: Important details are stored as vector embeddings with metadata
18
+ 4. **Memory Retrieval**: When relevant, the AI recalls past memories to provide context
19
+ 5. **Timeline View**: View your memory timeline and statistics
20
+
21
+ ## 💡 Memory Recording Examples
22
+
23
+ The system automatically remembers:
24
+ - Personal preferences: "I love pizza and hate mushrooms"
25
+ - Important facts: "My birthday is December 15th"
26
+ - Locations: "I live in New York"
27
+ - Work/Study: "I work at Google", "I study computer science"
28
+ - Favorites: "My favorite color is blue"
29
+
30
+ ## 🏗️ Architecture
31
+
32
+ ```
33
+ space_app.py # Main application (optimized for HF Spaces)
34
+ ├── memory_manager.py # Memory storage and retrieval
35
+ ├── chat_interface.py # Hugging Face model integration
36
+ ├── config.py # Configuration settings
37
+ └── space_requirements.txt # Dependencies for HF Spaces
38
+ ```
39
+
40
+ ## 📦 Dependencies
41
+
42
+ - **Core**: torch, transformers, gradio
43
+ - **Memory**: faiss-cpu, sentence-transformers
44
+ - **Utilities**: numpy, pandas, python-dotenv, rich
45
+
46
+ ## 🔧 Local Development
47
+
48
+ ### Installation
49
+
50
+ 1. Clone this repository
51
+ 2. Install dependencies:
52
+ ```bash
53
+ pip install -r space_requirements.txt
54
+ ```
55
+ 3. Run the application:
56
+ ```bash
57
+ python space_app.py
58
+ ```
59
+
60
+ ### Testing
61
+
62
+ Run the test script to verify everything works:
63
+ ```bash
64
+ python test_app.py
65
+ ```
66
+
67
+ ## ☁️ Deploying to Hugging Face Spaces
68
+
69
+ ### Option 1: Direct Upload (Recommended)
70
+
71
+ 1. **Go to [Hugging Face Spaces](https://huggingface.co/spaces)**
72
+ 2. **Click "Create new Space"**
73
+ 3. **Choose a name** for your Space
74
+ 4. **Select "Gradio"** as the Space type
75
+ 5. **Choose "Public"** visibility
76
+ 6. **Upload the files**:
77
+ - `space_app.py` → Rename to `app.py`
78
+ - `memory_manager.py`
79
+ - `chat_interface.py`
80
+ - `config.py`
81
+ - `space_requirements.txt` → Rename to `requirements.txt`
82
+ - `README_SPACES.md` → Rename to `README.md`
83
+
84
+ 7. **Commit and push** to create your Space!
85
+
86
+ ### Option 2: Git Clone
87
+
88
+ 1. **Create a new Space** on Hugging Face
89
+ 2. **Clone your Space locally**:
90
+ ```bash
91
+ git clone https://huggingface.co/spaces/your-username/your-space-name
92
+ cd your-space-name
93
+ ```
94
+
95
+ 3. **Copy the files**:
96
+ ```bash
97
+ cp /path/to/your/hf-memory-chat/space_app.py app.py
98
+ cp /path/to/your/hf-memory-chat/memory_manager.py .
99
+ cp /path/to/your/hf-memory-chat/chat_interface.py .
100
+ cp /path/to/your/hf-memory-chat/config.py .
101
+ cp /path/to/your/hf-memory-chat/space_requirements.txt requirements.txt
102
+ cp /path/to/your/hf-memory-chat/README_SPACES.md README.md
103
+ ```
104
+
105
+ 4. **Push to HF**:
106
+ ```bash
107
+ git add .
108
+ git commit -m "Initial commit: Memory Chat application"
109
+ git push origin main
110
+ ```
111
+
112
+ ## ⚙️ Configuration
113
+
114
+ ### Environment Variables
115
+
116
+ HF Spaces automatically sets up the environment, but you can customize:
117
+
118
+ - `PORT`: The port to run on (automatically set by Spaces)
119
+ - `SPACE_ID`: Space identifier (automatically set)
120
+
121
+ ### Model Configuration
122
+
123
+ The application uses `microsoft/DialoGPT-small` by default, which is optimized for:
124
+ - Fast loading times
125
+ - Good conversational quality
126
+ - Lower resource usage
127
+
128
+ ## 🧠 Memory System Details
129
+
130
+ ### Storage
131
+ - **Location**: `/tmp/memories` on HF Spaces (persistent)
132
+ - **Format**: JSON for memories, Markdown for timeline
133
+ - **Indexing**: FAISS for fast similarity search
134
+
135
+ ### Memory Types
136
+ - **General**: General information and facts
137
+ - **Conversation**: Important details from chats
138
+ - **Preferences**: Likes, dislikes, favorites
139
+ - **Important**: Critical information marked as important
140
+
141
+ ### Automatic Recording
142
+ Memories are automatically recorded when:
143
+ - User explicitly requests memory recording
144
+ - Important keywords are detected
145
+ - Personal information patterns are found
146
+ - High importance score is calculated
147
+
148
+ ## 🎨 UI Features
149
+
150
+ ### Chat Interface
151
+ - Clean, responsive design
152
+ - Send messages with Enter key
153
+ - Clear conversation history
154
+ - Automatic memory recording indicators
155
+
156
+ ### Memory Management
157
+ - View memory statistics
158
+ - See recent memories
159
+ - Clear all memories
160
+ - Refresh memory display
161
+
162
+ ### About Section
163
+ - Detailed documentation
164
+ - Usage instructions
165
+ - Feature explanations
166
+
167
+ ## 🚀 Performance Optimizations
168
+
169
+ ### For HF Spaces
170
+ - **Model Selection**: Uses DialoGPT-small for faster loading
171
+ - **Memory Storage**: Optimized for persistent storage
172
+ - **Error Handling**: Graceful fallbacks for model loading
173
+ - **Resource Management**: Efficient memory usage
174
+
175
+ ### Local Development
176
+ - **GPU Support**: Automatic GPU detection if available
177
+ - **Caching**: Model loading optimization
178
+ - **Error Recovery**: Fallback to simple text generation
179
+
180
+ ## 🐛 Troubleshooting
181
+
182
+ ### Common Issues
183
+
184
+ 1. **Model Loading Errors**
185
+ - Usually temporary network issues
186
+ - Application falls back to simple text generation
187
+ - Try refreshing the page
188
+
189
+ 2. **Memory Not Persisting**
190
+ - Ensure you're using the correct app.py file
191
+ - Check that `/tmp/memories` directory is writable
192
+ - Verify Space has sufficient storage
193
+
194
+ 3. **Slow Responses**
195
+ - First-time model loading can be slow
196
+ - Subsequent requests are cached
197
+ - Consider using smaller models for faster responses
198
+
199
+ ### Getting Help
200
+
201
+ - **Hugging Face Community**: [HF Forums](https://discuss.huggingface.co/)
202
+ - **GitHub Issues**: Report bugs and feature requests
203
+ - **Documentation**: Check the About section in the app
204
+
205
+ ## 📄 License
206
+
207
+ MIT License - see LICENSE file for details
208
+
209
+ ## 🤝 Contributing
210
+
211
+ 1. Fork the repository
212
+ 2. Create a feature branch
213
+ 3. Make your changes
214
+ 4. Add tests for your changes
215
+ 5. Submit a pull request
216
+
217
+ ## 🙏 Acknowledgments
218
+
219
+ - **Hugging Face**: For providing the amazing ecosystem and Spaces platform
220
+ - **Microsoft**: For the DialoGPT models
221
+ - **FAISS Team**: For efficient similarity search
222
+ - **Gradio Team**: For the excellent UI framework
223
+
224
+ ---
225
+
226
+ **Built with ❤️ using Hugging Face, Gradio, and the power of AI memories**
__pycache__/app.cpython-312.pyc ADDED
Binary file (13.1 kB). View file
 
__pycache__/chat_interface.cpython-312.pyc ADDED
Binary file (4.85 kB). View file
 
__pycache__/memory_manager.cpython-312.pyc ADDED
Binary file (11.2 kB). View file
 
app.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List, Dict, Optional
3
+ import gradio as gr
4
+ from memory_manager import MemoryManager
5
+ from chat_interface import HuggingFaceChat
6
+ from rich.console import Console
7
+
8
+ console = Console()
9
+
10
+ class MemoryChatApp:
11
+ """Main application that combines memory management with Hugging Face chat."""
12
+
13
+ def __init__(self):
14
+ """Initialize the application."""
15
+ self.memory_manager = MemoryManager()
16
+ self.chat_interface = HuggingFaceChat()
17
+
18
+ # Conversation history
19
+ self.conversation_history = []
20
+
21
+ # Load existing memories
22
+ summary = self.memory_manager.get_summary()
23
+ console.print(f"[blue]Loaded {summary['total_memories']} memories[/blue]")
24
+
25
+ def should_record_memory(self, user_input: str, ai_response: str) -> bool:
26
+ """
27
+ Determine if the conversation should be recorded as a memory.
28
+
29
+ Args:
30
+ user_input: The user's input
31
+ ai_response: The AI's response
32
+
33
+ Returns:
34
+ True if this should be recorded as a memory
35
+ """
36
+ # Keywords that indicate important information
37
+ important_keywords = [
38
+ "remember", "important", "note", "fact", "detail", "information",
39
+ "love", "hate", "like", "dislike", "favorite", "never", "always",
40
+ "birthday", "anniversary", "special", "urgent", "must", "should"
41
+ ]
42
+
43
+ # Combine user input and AI response for analysis
44
+ combined_text = f"{user_input} {ai_response}".lower()
45
+
46
+ # Check for important keywords
47
+ for keyword in important_keywords:
48
+ if keyword in combined_text:
49
+ return True
50
+
51
+ # Check for personal information patterns
52
+ personal_patterns = [
53
+ "my name is", "i live in", "i work at", "i study", "my birthday",
54
+ "my favorite", "i love", "i hate", "i like", "i dislike"
55
+ ]
56
+
57
+ for pattern in personal_patterns:
58
+ if pattern in combined_text:
59
+ return True
60
+
61
+ return False
62
+
63
+ def extract_memory_content(self, user_input: str, ai_response: str) -> str:
64
+ """
65
+ Extract the most important information to store as a memory.
66
+
67
+ Args:
68
+ user_input: The user's input
69
+ ai_response: The AI's response
70
+
71
+ Returns:
72
+ The content to store as a memory
73
+ """
74
+ # If user explicitly wants to record something
75
+ if any(word in user_input.lower() for word in ["remember", "note", "save"]):
76
+ return user_input
77
+
78
+ # Extract personal information
79
+ personal_info = []
80
+ if "my name is" in user_input.lower():
81
+ personal_info.append("User shared their name")
82
+ if "i live in" in user_input.lower():
83
+ personal_info.append("User shared their location")
84
+ if "i work at" in user_input.lower():
85
+ personal_info.append("User shared their workplace")
86
+ if "i study" in user_input.lower():
87
+ personal_info.append("User shared their studies")
88
+ if "my birthday" in user_input.lower():
89
+ personal_info.append("User shared their birthday")
90
+ if "my favorite" in user_input.lower():
91
+ personal_info.append("User shared a favorite thing")
92
+
93
+ if personal_info:
94
+ return f"User mentioned: {', '.join(personal_info)}. Details: {user_input}"
95
+
96
+ # Default to user input if no specific patterns found
97
+ return user_input
98
+
99
+ def chat_with_memory(self, user_input: str) -> str:
100
+ """
101
+ Chat with the AI while managing memories.
102
+
103
+ Args:
104
+ user_input: The user's input
105
+
106
+ Returns:
107
+ The AI's response
108
+ """
109
+ # Check if model is available
110
+ if not self.chat_interface.check_model_availability():
111
+ return "I'm sorry, but I couldn't load the AI model. Please check your internet connection."
112
+
113
+ # Add user input to conversation history
114
+ self.conversation_history.append({"role": "user", "content": user_input})
115
+
116
+ # Retrieve relevant memories to provide context
117
+ relevant_memories = self.memory_manager.retrieve_memories(user_input, k=3)
118
+
119
+ # Build context from memories
120
+ context = ""
121
+ if relevant_memories:
122
+ context = "Relevant memories:\n"
123
+ for memory in relevant_memories[:2]: # Limit to 2 most relevant
124
+ context += f"- {memory['content']}\n"
125
+ context += "\n"
126
+
127
+ # Build the prompt with context and conversation history
128
+ prompt = self.build_prompt(user_input, context)
129
+
130
+ # Generate AI response
131
+ ai_response = self.chat_interface.generate_response(prompt)
132
+
133
+ # Add AI response to conversation history
134
+ self.conversation_history.append({"role": "assistant", "content": ai_response})
135
+
136
+ # Check if we should record a memory
137
+ if self.should_record_memory(user_input, ai_response):
138
+ memory_content = self.extract_memory_content(user_input, ai_response)
139
+ context_info = f"During conversation at {self.get_current_time()}"
140
+
141
+ self.memory_manager.add_memory(
142
+ content=memory_content,
143
+ context=context_info,
144
+ memory_type="conversation"
145
+ )
146
+
147
+ return ai_response
148
+
149
+ def build_prompt(self, user_input: str, context: str) -> str:
150
+ """
151
+ Build the prompt for the AI model.
152
+
153
+ Args:
154
+ user_input: The user's input
155
+ context: Context from relevant memories
156
+
157
+ Returns:
158
+ The prompt to send to the AI model
159
+ """
160
+ prompt = f"{context}Human: {user_input}\nAI: "
161
+ return prompt
162
+
163
+ def get_current_time(self) -> str:
164
+ """Get current time in a readable format."""
165
+ import datetime
166
+ return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
167
+
168
+ def get_memories_summary(self) -> str:
169
+ """Get a summary of stored memories."""
170
+ summary = self.memory_manager.get_summary()
171
+ memory_types = summary['memory_types']
172
+
173
+ summary_text = f"""
174
+ ## Memory Summary
175
+
176
+ **Total Memories:** {summary['total_memories']}
177
+
178
+ **Memory Types:**
179
+ """
180
+ for memory_type, count in memory_types.items():
181
+ summary_text += f"- {memory_type}: {count}\n"
182
+
183
+ return summary_text
184
+
185
+ def get_recent_memories(self) -> str:
186
+ """Get the most recent memories."""
187
+ recent_memories = self.memory_manager.get_recent_memories()
188
+ if not recent_memories:
189
+ return "No memories stored yet."
190
+
191
+ memory_text = "## Recent Memories\n\n"
192
+ for memory in recent_memories:
193
+ memory_text += f"**{memory['type'].title()}** ({memory['timestamp'][:19]}):\n"
194
+ memory_text += f"{memory['content']}\n\n"
195
+
196
+ return memory_text
197
+
198
+ def clear_all_memories(self) -> str:
199
+ """Clear all memories."""
200
+ self.memory_manager.clear_memories()
201
+ return "All memories have been cleared."
202
+
203
+ def get_model_info(self) -> str:
204
+ """Get information about the AI model."""
205
+ info = self.chat_interface.get_model_info()
206
+ return f"""
207
+ ## Model Information
208
+
209
+ **Model:** {info['model_name']}
210
+ **Device:** {info['device']}
211
+ **Available:** {'Yes' if info['available'] else 'No'}
212
+ """
213
+
214
+ def run_gradio_interface(self):
215
+ """Run the Gradio interface."""
216
+ with gr.Blocks(title="Memory Chat") as demo:
217
+ gr.Markdown("# 🤖 Memory Chat with Hugging Face")
218
+
219
+ with gr.Tab("Chat"):
220
+ chatbot = gr.Chatbot()
221
+ msg = gr.Textbox(label="Message", placeholder="Type your message here...")
222
+ clear = gr.Button("Clear Conversation")
223
+
224
+ def user(user_message, history):
225
+ # Get AI response
226
+ ai_response = self.chat_with_memory(user_message)
227
+
228
+ # Update conversation history
229
+ if history is None:
230
+ history = []
231
+ history.append({"role": "user", "content": user_message})
232
+ history.append({"role": "assistant", "content": ai_response})
233
+ return "", history
234
+
235
+ def clear_history():
236
+ self.conversation_history = []
237
+ return None
238
+
239
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False)
240
+ clear.click(clear_history, None, chatbot, queue=False)
241
+
242
+ with gr.Tab("Memories"):
243
+ memories_summary = gr.Markdown(value=self.get_memories_summary())
244
+ recent_memories = gr.Markdown(value=self.get_recent_memories())
245
+ clear_memories_btn = gr.Button("Clear All Memories")
246
+ model_info = gr.Markdown(value=self.get_model_info())
247
+
248
+ def refresh_memories():
249
+ return self.get_memories_summary(), self.get_recent_memories()
250
+
251
+ refresh_btn = gr.Button("Refresh Memories")
252
+ refresh_btn.click(refresh_memories, outputs=[memories_summary, recent_memories])
253
+ clear_memories_btn.click(self.clear_all_memories, outputs=[])
254
+
255
+ with gr.Tab("About"):
256
+ gr.Markdown("""
257
+ ## About This Application
258
+
259
+ This application combines Hugging Face AI models with a memory system that records important information from your conversations.
260
+
261
+ ### Features:
262
+ - 🤖 Chat with Hugging Face models
263
+ - 💾 Automatic memory recording
264
+ - 📚 View and manage your memories
265
+ - 🔍 Search through your memories
266
+
267
+ ### How it works:
268
+ 1. Have a conversation with the AI
269
+ 2. The system automatically detects important information
270
+ 3. Important memories are stored and can be recalled in future conversations
271
+ 4. View your memory timeline and statistics
272
+
273
+ ### Memory Types:
274
+ - **General**: General information and facts
275
+ - **Conversation**: Important details from chats
276
+ - **Preferences**: Likes, dislikes, favorites
277
+ - **Important**: Critical information marked as important
278
+ """)
279
+
280
+ return demo
281
+
282
+ def main():
283
+ """Main entry point."""
284
+ console.print("[green]🚀 Starting Memory Chat Application...[/green]")
285
+
286
+ # Create and run the application
287
+ app = MemoryChatApp()
288
+
289
+ # Run Gradio interface
290
+ demo = app.run_gradio_interface()
291
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
292
+
293
+ if __name__ == "__main__":
294
+ main()
chat_interface.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
4
+ from typing import List, Dict, Optional
5
+ from rich.console import Console
6
+
7
+ console = Console()
8
+
9
+ class HuggingFaceChat:
10
+ """Interface for chatting with Hugging Face models."""
11
+
12
+ def __init__(self, model_name: str = "microsoft/DialoGPT-small"):
13
+ """
14
+ Initialize the chat interface.
15
+
16
+ Args:
17
+ model_name: The Hugging Face model to use
18
+ """
19
+ self.model_name = model_name
20
+ self.device = 0 if torch.cuda.is_available() else -1 # Use GPU if available
21
+
22
+ # Try loading the model with safetensors first
23
+ try:
24
+ console.print(f"[blue]Loading model: {model_name}[/blue]")
25
+ # Try to load with safetensors format first
26
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name, use_safetensors=True)
27
+ self.model = AutoModelForCausalLM.from_pretrained(model_name, use_safetensors=True)
28
+ self.chatbot = pipeline(
29
+ "text-generation",
30
+ model=self.model,
31
+ tokenizer=self.tokenizer,
32
+ device=self.device
33
+ )
34
+ console.print("[green]✓ Model loaded successfully[/green]")
35
+ except Exception as e:
36
+ console.print(f"[red]Error loading model with safetensors: {e}[/red]")
37
+ try:
38
+ # Fallback to regular loading
39
+ console.print("[yellow]Trying regular loading...[/yellow]")
40
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
41
+ self.model = AutoModelForCausalLM.from_pretrained(model_name)
42
+ self.chatbot = pipeline(
43
+ "text-generation",
44
+ model=self.model,
45
+ tokenizer=self.tokenizer,
46
+ device=self.device
47
+ )
48
+ console.print("[green]✓ Model loaded successfully[/green]")
49
+ except Exception as e2:
50
+ console.print(f"[red]Error loading model: {e2}[/red]")
51
+ console.print("[yellow]Falling back to simple text generation...[/yellow]")
52
+ self.chatbot = None
53
+
54
+ def generate_response(self, prompt: str, max_length: int = 1000) -> str:
55
+ """
56
+ Generate a response to a prompt.
57
+
58
+ Args:
59
+ prompt: The input prompt
60
+ max_length: Maximum length of the generated response
61
+
62
+ Returns:
63
+ The generated response
64
+ """
65
+ if not self.chatbot:
66
+ return "I'm sorry, but I couldn't load the model. Please check your internet connection and model availability."
67
+
68
+ try:
69
+ # Generate response
70
+ response = self.chatbot(
71
+ prompt,
72
+ max_length=max_length,
73
+ do_sample=True,
74
+ temperature=0.7,
75
+ top_p=0.9,
76
+ repetition_penalty=1.2,
77
+ pad_token_id=self.tokenizer.eos_token_id
78
+ )
79
+
80
+ # Extract the generated text
81
+ generated_text = response[0]['generated_text']
82
+
83
+ # Remove the prompt from the response if it's included
84
+ if generated_text.startswith(prompt):
85
+ generated_text = generated_text[len(prompt):].strip()
86
+
87
+ return generated_text
88
+
89
+ except Exception as e:
90
+ console.print(f"[red]Error generating response: {e}[/red]")
91
+ return "I'm sorry, but I encountered an error while generating a response."
92
+
93
+ def check_model_availability(self) -> bool:
94
+ """Check if the model is available."""
95
+ return self.chatbot is not None
96
+
97
+ def get_model_info(self) -> Dict:
98
+ """Get information about the loaded model."""
99
+ return {
100
+ "model_name": self.model_name,
101
+ "device": "GPU" if self.device == 0 else "CPU",
102
+ "available": self.chatbot is not None
103
+ }
config.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Configuration settings for the Memory Chat application.
3
+ """
4
+
5
+ # Model configuration
6
+ DEFAULT_MODEL = "microsoft/DialoGPT-medium"
7
+ ALTERNATIVE_MODELS = [
8
+ "microsoft/DialoGPT-small",
9
+ "microsoft/DialoGPT-large",
10
+ "facebook/blenderbot-400M-distill",
11
+ ]
12
+
13
+ # Memory configuration
14
+ MEMORY_DIR = "memories"
15
+ EMBEDDING_MODEL = "all-MiniLM-L6-v2"
16
+ MAX_RETRIEVED_MEMORIES = 5
17
+ MEMORY_IMPORTANCE_THRESHOLD = 0.7
18
+
19
+ # Chat configuration
20
+ MAX_RESPONSE_LENGTH = 1000
21
+ TEMPERATURE = 0.7
22
+ TOP_P = 0.9
23
+ REPETITION_PENALTY = 1.2
24
+
25
+ # UI configuration
26
+ GRADIO_TITLE = "Memory Chat with Hugging Face"
27
+ GRADIO_THEME = "soft"
28
+
29
+ # Keywords that trigger memory recording
30
+ MEMORY_TRIGGER_KEYWORDS = [
31
+ "remember", "note", "save", "important", "fact", "detail",
32
+ "my name is", "i live in", "i work at", "i study",
33
+ "my birthday", "my favorite", "i love", "i hate", "i like",
34
+ "never", "always", "often", "every", "daily", "weekly"
35
+ ]
36
+
37
+ # Memory types
38
+ MEMORY_TYPES = {
39
+ "general": "General information and facts",
40
+ "conversation": "Important details from chats",
41
+ "preference": "Likes, dislikes, favorites",
42
+ "important": "Critical information marked as important",
43
+ "personal": "Personal information and details"
44
+ }
deploy_to_spaces.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Direct upload script to Hugging Face Spaces.
4
+ This script will guide you through creating and uploading your Memory Chat application.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import subprocess
10
+ import webbrowser
11
+ from pathlib import Path
12
+
13
+ def check_prerequisites():
14
+ """Check if prerequisites are installed."""
15
+ print("🔍 Checking prerequisites...")
16
+
17
+ # Check if git is installed
18
+ try:
19
+ result = subprocess.run(['git', '--version'], capture_output=True, text=True)
20
+ if result.returncode == 0:
21
+ print("✅ Git is installed")
22
+ else:
23
+ print("❌ Git is not installed. Please install Git first.")
24
+ return False
25
+ except FileNotFoundError:
26
+ print("❌ Git is not installed. Please install Git first.")
27
+ return False
28
+
29
+ # Check if files exist
30
+ required_files = [
31
+ 'app.py',
32
+ 'memory_manager.py',
33
+ 'chat_interface.py',
34
+ 'config.py',
35
+ 'requirements.txt',
36
+ 'README.md'
37
+ ]
38
+
39
+ missing_files = []
40
+ for file in required_files:
41
+ if not os.path.exists(file):
42
+ missing_files.append(file)
43
+
44
+ if missing_files:
45
+ print(f"❌ Missing files: {', '.join(missing_files)}")
46
+ print("Please ensure all required files are in the current directory.")
47
+ return False
48
+ else:
49
+ print("✅ All required files found")
50
+
51
+ return True
52
+
53
+ def create_space():
54
+ """Guide user through creating a Space on Hugging Face."""
55
+ print("\n🌐 Creating Hugging Face Space...")
56
+
57
+ print("1. Open your web browser and go to: https://huggingface.co/spaces")
58
+ print("2. Sign in to your Hugging Face account")
59
+ print("3. Click 'Create new Space' (top right)")
60
+ print("4. Choose a Space name (e.g., 'your-username/memory-chat')")
61
+ print("5. Select 'Gradio' as the Space type")
62
+ print("6. Choose 'Public' visibility")
63
+ print("7. Click 'Create Space'")
64
+
65
+ input("\nPress Enter after you've created your Space...")
66
+
67
+ def get_space_url():
68
+ """Get the Space URL from user."""
69
+ print("\n📍 Please enter your Space URL:")
70
+ print("It should look like: https://huggingface.co/spaces/your-username/your-space-name")
71
+ space_url = input("Space URL: ").strip()
72
+
73
+ if not space_url.startswith("https://huggingface.co/spaces/"):
74
+ print("❌ Invalid URL format. Please enter a valid Hugging Face Space URL.")
75
+ return get_space_url()
76
+
77
+ return space_url
78
+
79
+ def clone_space_repo(space_url):
80
+ """Clone the Space repository."""
81
+ print(f"\n📥 Cloning Space repository: {space_url}")
82
+
83
+ # Extract the repo name from URL
84
+ repo_name = space_url.split('/')[-1]
85
+ username = space_url.split('/')[-2]
86
+
87
+ clone_url = f"https://huggingface.co/spaces/{username}/{repo_name}"
88
+
89
+ try:
90
+ subprocess.run(['git', 'clone', clone_url], check=True)
91
+ return repo_name
92
+ except subprocess.CalledProcessError as e:
93
+ print(f"❌ Failed to clone repository: {e}")
94
+ return None
95
+
96
+ def copy_files_to_repo(repo_name):
97
+ """Copy files to the cloned repository."""
98
+ print(f"\n📁 Copying files to {repo_name}...")
99
+
100
+ files_to_copy = [
101
+ ('app.py', 'app.py'),
102
+ ('memory_manager.py', 'memory_manager.py'),
103
+ ('chat_interface.py', 'chat_interface.py'),
104
+ ('config.py', 'config.py'),
105
+ ('requirements.txt', 'requirements.txt'),
106
+ ('README.md', 'README.md')
107
+ ]
108
+
109
+ for src, dst in files_to_copy:
110
+ try:
111
+ subprocess.run(['cp', src, f"{repo_name}/{dst}"], check=True)
112
+ print(f"✅ Copied {src} -> {repo_name}/{dst}")
113
+ except subprocess.CalledProcessError as e:
114
+ print(f"❌ Failed to copy {src}: {e}")
115
+ return False
116
+
117
+ return True
118
+
119
+ def commit_and_push(repo_name, username):
120
+ """Commit and push changes to the Space."""
121
+ print(f"\n🚀 Committing and pushing changes...")
122
+
123
+ try:
124
+ # Change to repo directory
125
+ os.chdir(repo_name)
126
+
127
+ # Add files
128
+ subprocess.run(['git', 'add', '.'], check=True)
129
+
130
+ # Commit
131
+ subprocess.run(['git', 'commit', '-m', 'Initial commit: Memory Chat application'], check=True)
132
+
133
+ # Push
134
+ subprocess.run(['git', 'push', 'origin', 'main'], check=True)
135
+
136
+ print("✅ Successfully pushed to Hugging Face Spaces!")
137
+ print(f"🌐 Your Space will be available at: https://huggingface.co/spaces/{username}/{repo_name}")
138
+
139
+ return True
140
+
141
+ except subprocess.CalledProcessError as e:
142
+ print(f"❌ Failed to commit/push: {e}")
143
+ return False
144
+
145
+ def main():
146
+ """Main deployment function."""
147
+ print("🚀 Memory Chat - Hugging Face Spaces Deployment")
148
+ print("=" * 50)
149
+
150
+ # Check prerequisites
151
+ if not check_prerequisites():
152
+ sys.exit(1)
153
+
154
+ # Create Space on Hugging Face
155
+ create_space()
156
+
157
+ # Get Space URL
158
+ space_url = get_space_url()
159
+ username = space_url.split('/')[-2]
160
+
161
+ # Clone the Space repository
162
+ repo_name = clone_space_repo(space_url)
163
+ if not repo_name:
164
+ sys.exit(1)
165
+
166
+ # Copy files
167
+ if not copy_files_to_repo(repo_name):
168
+ sys.exit(1)
169
+
170
+ # Commit and push
171
+ if commit_and_push(repo_name, username):
172
+ print("\n🎉 Deployment successful!")
173
+ print("Your Space will build automatically and be available shortly.")
174
+ print("Check the 'Logs' tab in your Space for build status.")
175
+ else:
176
+ print("\n❌ Deployment failed. Please check the error messages above.")
177
+
178
+ if __name__ == "__main__":
179
+ main()
git_deploy.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Git-based deployment to Hugging Face Spaces.
4
+ This script will guide you through creating and deploying via Git.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import subprocess
10
+ import getpass
11
+ import webbrowser
12
+ from pathlib import Path
13
+
14
+ def run_command(command, description=""):
15
+ """Run a shell command and return success status."""
16
+ print(f"🔄 {description}")
17
+ try:
18
+ result = subprocess.run(command, shell=True, check=True, text=True, capture_output=True)
19
+ if result.stdout:
20
+ print(f"✅ {result.stdout.strip()}")
21
+ return True
22
+ except subprocess.CalledProcessError as e:
23
+ print(f"❌ Error: {e}")
24
+ if e.stderr:
25
+ print(f"Error details: {e.stderr.strip()}")
26
+ return False
27
+
28
+ def check_git():
29
+ """Check if git is installed and configured."""
30
+ print("🔍 Checking Git...")
31
+ if not run_command("git --version", "Checking Git installation"):
32
+ print("❌ Git is not installed. Please install Git first.")
33
+ return False
34
+
35
+ # Check if user is configured
36
+ name_result = subprocess.run("git config user.name", shell=True, capture_output=True, text=True)
37
+ email_result = subprocess.run("git config user.email", shell=True, capture_output=True, text=True)
38
+
39
+ if not name_result.stdout.strip():
40
+ print("⚠️ Git user name not configured")
41
+ name = input("Enter your Git user name: ")
42
+ run_command(f'git config --global user.name "{name}"', "Setting Git user name")
43
+
44
+ if not email_result.stdout.strip():
45
+ print("⚠️ Git user email not configured")
46
+ email = input("Enter your Git user email: ")
47
+ run_command(f'git config --global user.email "{email}"', "Setting Git user email")
48
+
49
+ return True
50
+
51
+ def get_hf_token():
52
+ """Get Hugging Face API token."""
53
+ print("\n🔐 Getting Hugging Face credentials...")
54
+
55
+ # Check if token is set as environment variable
56
+ hf_token = os.getenv('HF_TOKEN')
57
+ if hf_token:
58
+ print("✅ Found HF_TOKEN environment variable")
59
+ return hf_token
60
+
61
+ print("Please get your Hugging Face API token:")
62
+ print("1. Go to: https://huggingface.co/settings/tokens")
63
+ print("2. Click 'New token'")
64
+ print("3. Set name: 'spaces-deploy'")
65
+ print("4. Set role: 'write'")
66
+ print("5. Copy the token")
67
+
68
+ webbrowser.open("https://huggingface.co/settings/tokens")
69
+
70
+ hf_token = getpass.getpass("Enter your Hugging Face API token: ")
71
+ return hf_token
72
+
73
+ def create_space():
74
+ """Create a new Space on Hugging Face."""
75
+ print("\n🌐 Creating Hugging Face Space...")
76
+
77
+ username = input("Enter your Hugging Face username: ")
78
+ space_name = input("Enter your Space name (e.g., 'memory-chat'): ")
79
+
80
+ # Create Space via API
81
+ hf_token = get_hf_token()
82
+
83
+ api_url = f"https://huggingface.co/api/spaces/{username}/{space_name}"
84
+ create_cmd = f'curl -X POST {api_url} -H "Authorization: Bearer {hf_token}" -H "Content-Type: application/json" -d \'{{"private": false, "sdk": "gradio"}}\''
85
+
86
+ print("Creating Space...")
87
+ if run_command(create_cmd, "Creating Space on Hugging Face"):
88
+ print(f"✅ Space created: https://huggingface.co/spaces/{username}/{space_name}")
89
+ return username, space_name
90
+ else:
91
+ print("❌ Failed to create Space. Please check your credentials and try again.")
92
+ return None, None
93
+
94
+ def setup_git_remote(username, space_name, hf_token):
95
+ """Setup Git remote for the Space."""
96
+ print(f"\n🔗 Setting up Git remote for {username}/{space_name}...")
97
+
98
+ remote_url = f"https://USER:TOKEN@huggingface.co/spaces/{username}/{space_name}"
99
+ remote_url = remote_url.replace("USER", username).replace("TOKEN", hf_token)
100
+
101
+ if run_command(f"git remote add origin {remote_url}", "Adding Git remote"):
102
+ return True
103
+ else:
104
+ # Try removing and re-adding
105
+ run_command("git remote remove origin", "Removing existing remote")
106
+ return run_command(f"git remote add origin {remote_url}", "Adding Git remote")
107
+
108
+ def deploy_to_spaces():
109
+ """Main deployment function."""
110
+ print("🚀 Memory Chat - Git Deployment to Hugging Face Spaces")
111
+ print("=" * 60)
112
+
113
+ # Check prerequisites
114
+ if not check_git():
115
+ sys.exit(1)
116
+
117
+ # Check if we're in a git repo
118
+ if not os.path.exists(".git"):
119
+ print("🔄 Initializing Git repository...")
120
+ if not run_command("git init", "Initializing Git repository"):
121
+ sys.exit(1)
122
+
123
+ # Check if files exist
124
+ required_files = ['app.py', 'memory_manager.py', 'chat_interface.py', 'config.py', 'requirements.txt', 'README.md']
125
+ missing_files = [f for f in required_files if not os.path.exists(f)]
126
+
127
+ if missing_files:
128
+ print(f"❌ Missing files: {', '.join(missing_files)}")
129
+ print("Please ensure all required files are in the current directory.")
130
+ sys.exit(1)
131
+
132
+ # Create Space or get existing Space details
133
+ choice = input("\nDo you want to create a new Space? (y/n): ").lower().strip()
134
+ if choice == 'y':
135
+ username, space_name = create_space()
136
+ if not username:
137
+ sys.exit(1)
138
+ else:
139
+ username = input("Enter your Hugging Face username: ")
140
+ space_name = input("Enter your existing Space name: ")
141
+
142
+ # Setup Git remote
143
+ hf_token = get_hf_token()
144
+ if not setup_git_remote(username, space_name, hf_token):
145
+ print("❌ Failed to setup Git remote")
146
+ sys.exit(1)
147
+
148
+ # Add files and commit
149
+ print("\n📁 Adding files to Git...")
150
+ if not run_command("git add .", "Adding all files"):
151
+ sys.exit(1)
152
+
153
+ if not run_command('git commit -m "Initial commit: Memory Chat application"', "Creating commit"):
154
+ sys.exit(1)
155
+
156
+ # Push to Hugging Face
157
+ print("\n🚀 Pushing to Hugging Face Spaces...")
158
+ if not run_command("git push -u origin main", "Pushing to remote"):
159
+ print("❌ Failed to push to remote. Trying with force...")
160
+ if not run_command("git push -u origin main --force", "Force pushing to remote"):
161
+ sys.exit(1)
162
+
163
+ print(f"\n🎉 Successfully deployed to: https://huggingface.co/spaces/{username}/{space_name}")
164
+ print("🌐 Your Space will build automatically. Check the 'Logs' tab for progress.")
165
+
166
+ return username, space_name
167
+
168
+ def main():
169
+ """Main entry point."""
170
+ if len(sys.argv) > 1 and sys.argv[1] == "--help":
171
+ print(__doc__)
172
+ sys.exit(0)
173
+
174
+ try:
175
+ deploy_to_spaces()
176
+ except KeyboardInterrupt:
177
+ print("\n❌ Deployment cancelled by user")
178
+ sys.exit(1)
179
+ except Exception as e:
180
+ print(f"\n❌ Deployment failed: {e}")
181
+ sys.exit(1)
182
+
183
+ if __name__ == "__main__":
184
+ main()
memories/memories.json ADDED
@@ -0,0 +1,791 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "id": 1,
4
+ "content": "User mentioned: User shared their name. Details: hello my name is edwin mauricio",
5
+ "context": "During conversation at 2026-01-09 22:25:16",
6
+ "type": "conversation",
7
+ "timestamp": "2026-01-09T22:25:17.112604",
8
+ "embedding": [
9
+ -0.057125337421894073,
10
+ -0.008446086198091507,
11
+ -0.07326115667819977,
12
+ -0.0026685793418437243,
13
+ -0.05792270228266716,
14
+ -0.015340020880103111,
15
+ 0.0979149118065834,
16
+ -0.0033453742507845163,
17
+ -0.0009754750062711537,
18
+ -0.04974544048309326,
19
+ 0.009946444071829319,
20
+ -0.021322263404726982,
21
+ 0.02255190908908844,
22
+ 0.011175232008099556,
23
+ -0.0348091684281826,
24
+ 0.03492099419236183,
25
+ -0.006262023933231831,
26
+ 0.002294063102453947,
27
+ -0.03296710178256035,
28
+ -0.06508582830429077,
29
+ -0.05960575118660927,
30
+ 0.00016545435937587172,
31
+ -0.05329013243317604,
32
+ 0.010785967111587524,
33
+ 0.07438857853412628,
34
+ -0.007583011873066425,
35
+ -0.002487051533535123,
36
+ 0.09221069514751434,
37
+ -0.03870362043380737,
38
+ 0.01354052685201168,
39
+ 0.020654771476984024,
40
+ -0.027539966627955437,
41
+ 0.09750374406576157,
42
+ 0.0656624585390091,
43
+ -0.042317237704992294,
44
+ -0.02733740396797657,
45
+ -0.08252953737974167,
46
+ -0.005312549881637096,
47
+ -0.010010665282607079,
48
+ -0.08037310838699341,
49
+ -0.006242047529667616,
50
+ -0.03140488639473915,
51
+ -0.006270831450819969,
52
+ 0.06866245716810226,
53
+ -0.07823919504880905,
54
+ 0.08782817423343658,
55
+ 0.021853437647223473,
56
+ 0.04021047428250313,
57
+ 0.02399042434990406,
58
+ 0.09958421438932419,
59
+ -0.08803551644086838,
60
+ -0.026885293424129486,
61
+ 0.028302989900112152,
62
+ -0.006180956494063139,
63
+ 0.015449032187461853,
64
+ -0.023429473862051964,
65
+ -2.770853097899817e-05,
66
+ 0.06675168126821518,
67
+ -0.01881526969373226,
68
+ -0.03623613715171814,
69
+ -0.0446024015545845,
70
+ -0.0018725040135905147,
71
+ -0.03358656167984009,
72
+ 0.0025525959208607674,
73
+ 0.006960983853787184,
74
+ -0.04203746095299721,
75
+ -0.07680106908082962,
76
+ -0.025578830391168594,
77
+ 0.05235536769032478,
78
+ -0.06356118619441986,
79
+ 0.010259767062962055,
80
+ 0.0643501728773117,
81
+ -0.007683092728257179,
82
+ -0.01564478687942028,
83
+ 0.010853197425603867,
84
+ 0.043562620878219604,
85
+ -0.006737628020346165,
86
+ -0.0021607333328574896,
87
+ -0.037271786481142044,
88
+ 0.0022986254189163446,
89
+ -0.03336505964398384,
90
+ 0.01152387447655201,
91
+ -0.08332626521587372,
92
+ -0.08827913552522659,
93
+ -0.01808939315378666,
94
+ 0.06315665692090988,
95
+ -0.027659477666020393,
96
+ -0.05011877790093422,
97
+ -0.012806248851120472,
98
+ -0.037625402212142944,
99
+ 0.0910073071718216,
100
+ 0.10150371491909027,
101
+ 0.06187543645501137,
102
+ -0.04064022749662399,
103
+ -0.04699157550930977,
104
+ -0.018568649888038635,
105
+ 0.009093087166547775,
106
+ 0.08078845590353012,
107
+ -0.16335779428482056,
108
+ 0.09966878592967987,
109
+ -0.047211308032274246,
110
+ 0.06600812822580338,
111
+ 0.016125407069921494,
112
+ 0.012649456970393658,
113
+ 0.04208759218454361,
114
+ 0.06756006181240082,
115
+ -0.008905795402824879,
116
+ 0.008182586170732975,
117
+ -0.022753743454813957,
118
+ -0.013720559887588024,
119
+ -0.005981684196740389,
120
+ -0.02735157683491707,
121
+ -0.09707805514335632,
122
+ -0.01930655911564827,
123
+ 0.07630596309900284,
124
+ -0.0021960127633064985,
125
+ -0.023808499798178673,
126
+ 0.036347340792417526,
127
+ 0.03259022533893585,
128
+ -0.016531927511096,
129
+ -0.029386838898062706,
130
+ 0.0006996437441557646,
131
+ -0.043099209666252136,
132
+ 0.013572637923061848,
133
+ -0.04598405584692955,
134
+ 0.02197236940264702,
135
+ 0.018159834668040276,
136
+ -3.8097806348461397e-34,
137
+ 0.019611947238445282,
138
+ 0.052307698875665665,
139
+ 0.04324403405189514,
140
+ 0.08529195189476013,
141
+ -0.044940344989299774,
142
+ -0.0027374771889299154,
143
+ -0.10778433829545975,
144
+ 0.00043052202090620995,
145
+ -0.06361633539199829,
146
+ -0.11566772311925888,
147
+ 0.0866595134139061,
148
+ 0.07818538695573807,
149
+ 0.04759884625673294,
150
+ -0.03842480108141899,
151
+ -0.027971411123871803,
152
+ -0.002866580383852124,
153
+ 0.029747571796178818,
154
+ -0.008215673267841339,
155
+ 0.03134743124246597,
156
+ 0.12150918692350388,
157
+ 0.011035402305424213,
158
+ -0.05886666476726532,
159
+ 0.030577510595321655,
160
+ 0.0692368820309639,
161
+ -0.014443919993937016,
162
+ -0.024542514234781265,
163
+ 0.02816048637032509,
164
+ -0.09045267850160599,
165
+ 0.15432702004909515,
166
+ 0.038488246500492096,
167
+ -0.023578844964504242,
168
+ 0.05558973178267479,
169
+ -0.03265468031167984,
170
+ -0.01619907096028328,
171
+ -0.0043658665381371975,
172
+ 0.050767477601766586,
173
+ 0.04110734164714813,
174
+ -0.05129428207874298,
175
+ -0.10075933486223221,
176
+ 0.051519718021154404,
177
+ 0.024081239476799965,
178
+ 0.017909986898303032,
179
+ -0.03146861866116524,
180
+ -0.04663139581680298,
181
+ -0.1365085244178772,
182
+ -0.034571852535009384,
183
+ -0.015411549247801304,
184
+ 0.11987785249948502,
185
+ 0.016943957656621933,
186
+ -0.0049460092559456825,
187
+ -0.07557415962219238,
188
+ 0.004541031084954739,
189
+ -0.10237791389226913,
190
+ 0.023688582703471184,
191
+ 0.007004923187196255,
192
+ -0.04844467341899872,
193
+ -0.028594058007001877,
194
+ 0.026007648557424545,
195
+ -0.039679963141679764,
196
+ -0.03582621365785599,
197
+ 0.027910927310585976,
198
+ 0.03410184755921364,
199
+ 0.03208622708916664,
200
+ 0.005524757318198681,
201
+ -0.06722851097583771,
202
+ -0.09288894385099411,
203
+ 0.007131680846214294,
204
+ -0.012614968232810497,
205
+ 0.049690842628479004,
206
+ 0.026632025837898254,
207
+ -0.007178872358053923,
208
+ -0.007110861595720053,
209
+ 0.03837954252958298,
210
+ 0.01662914827466011,
211
+ -0.06606756895780563,
212
+ -0.007788670249283314,
213
+ -0.042646374553442,
214
+ 0.07128605991601944,
215
+ -0.006830724887549877,
216
+ 0.027400994673371315,
217
+ 0.01368551142513752,
218
+ -0.032182540744543076,
219
+ -0.044077068567276,
220
+ -0.04613516107201576,
221
+ -0.09208519756793976,
222
+ 0.11833278089761734,
223
+ -0.07311288267374039,
224
+ -0.0008083946304395795,
225
+ -0.11028492450714111,
226
+ 0.03174746409058571,
227
+ 0.0027827059384435415,
228
+ 0.07041648775339127,
229
+ 0.08908120542764664,
230
+ 0.07946006208658218,
231
+ -0.05757908523082733,
232
+ -3.122636458112096e-33,
233
+ -0.02531912364065647,
234
+ 0.00385535997338593,
235
+ -0.019620083272457123,
236
+ -0.0665917620062828,
237
+ 0.04982120916247368,
238
+ -0.05796438083052635,
239
+ -0.04772398993372917,
240
+ 0.08149518817663193,
241
+ -0.08067349344491959,
242
+ 0.031712692230939865,
243
+ 0.03125898540019989,
244
+ 0.0011805040994659066,
245
+ 0.023329248651862144,
246
+ -0.024804499000310898,
247
+ -0.008077752776443958,
248
+ 0.015345391817390919,
249
+ 0.08851150423288345,
250
+ 0.04382757842540741,
251
+ -0.009666668251156807,
252
+ -0.05505415424704552,
253
+ -0.05158616974949837,
254
+ 0.06651522219181061,
255
+ -0.05985570326447487,
256
+ -0.02294558845460415,
257
+ 0.009721768088638783,
258
+ -0.0520574152469635,
259
+ 0.06250109523534775,
260
+ -0.006866733077913523,
261
+ -0.021205900236964226,
262
+ -0.05674334615468979,
263
+ 0.013122009113430977,
264
+ 0.07283326238393784,
265
+ -0.1287110447883606,
266
+ -0.11028259247541428,
267
+ -0.06954318284988403,
268
+ 0.030362773686647415,
269
+ -0.033978335559368134,
270
+ 0.10428588837385178,
271
+ 0.013802451081573963,
272
+ -0.004419572651386261,
273
+ 0.033986568450927734,
274
+ 0.08443409949541092,
275
+ 0.012827146798372269,
276
+ -0.00836518406867981,
277
+ -0.07776367664337158,
278
+ -0.00741546880453825,
279
+ -0.02556561306118965,
280
+ -0.06659505516290665,
281
+ -0.00032322993502020836,
282
+ 0.07700251042842865,
283
+ 0.017850907519459724,
284
+ -0.09126944839954376,
285
+ 0.047602418810129166,
286
+ -0.08610661327838898,
287
+ -0.011727987788617611,
288
+ 0.001727365073747933,
289
+ 0.0655781552195549,
290
+ -0.020107639953494072,
291
+ 0.06260063499212265,
292
+ -0.01636842079460621,
293
+ -0.07583952695131302,
294
+ 0.005413348320871592,
295
+ -0.06524797528982162,
296
+ 0.08053403347730637,
297
+ 0.03917818143963814,
298
+ -0.02600565366446972,
299
+ -0.010719946585595608,
300
+ 0.03897366672754288,
301
+ 0.012868308462202549,
302
+ -0.021330857649445534,
303
+ 0.08201935887336731,
304
+ -0.04026496782898903,
305
+ 0.02742106094956398,
306
+ 0.03216073662042618,
307
+ -0.010248266160488129,
308
+ 0.025661468505859375,
309
+ -0.006426472682505846,
310
+ 0.0027222500648349524,
311
+ 0.0059382617473602295,
312
+ 0.06493712216615677,
313
+ 0.018517453223466873,
314
+ 0.0663008987903595,
315
+ 0.009702255018055439,
316
+ 0.03144288435578346,
317
+ 0.010866508819162846,
318
+ -0.041125524789094925,
319
+ 0.04375699162483215,
320
+ 0.050250548869371414,
321
+ 0.009397868998348713,
322
+ 0.05026782676577568,
323
+ 0.0239596925675869,
324
+ -0.015477035194635391,
325
+ -0.03177541121840477,
326
+ -0.10046987235546112,
327
+ -0.03420412167906761,
328
+ -2.448786062814179e-08,
329
+ 0.006381123326718807,
330
+ -0.022108735516667366,
331
+ 0.036654602736234665,
332
+ 0.09345582127571106,
333
+ -0.018864160403609276,
334
+ 0.05616375803947449,
335
+ 0.015253727324306965,
336
+ 0.052468426525592804,
337
+ 0.005437702871859074,
338
+ 0.05385417863726616,
339
+ -0.04094225540757179,
340
+ 0.03294241055846214,
341
+ -0.005734832491725683,
342
+ 0.014899514615535736,
343
+ 0.09180409461259842,
344
+ -0.05105292797088623,
345
+ 0.00816957838833332,
346
+ 0.05021567642688751,
347
+ -0.043644584715366364,
348
+ -0.061980511993169785,
349
+ -0.05464288592338562,
350
+ 0.0018051754450425506,
351
+ -0.010898329317569733,
352
+ -0.050912417471408844,
353
+ 0.019909996539354324,
354
+ 0.019790442660450935,
355
+ 0.003015709575265646,
356
+ -0.006313270423561335,
357
+ -0.08978044241666794,
358
+ -0.025397317484021187,
359
+ -0.04049055278301239,
360
+ 0.07724948972463608,
361
+ 0.0444415882229805,
362
+ -0.031838931143283844,
363
+ -0.01125660166144371,
364
+ 0.019191239029169083,
365
+ 0.0001980650267796591,
366
+ -0.029844986274838448,
367
+ -0.03391929715871811,
368
+ -0.04952402040362358,
369
+ -0.06361277401447296,
370
+ 0.0064875963144004345,
371
+ 0.03808775544166565,
372
+ 0.012116416357457638,
373
+ 0.07537489384412766,
374
+ 0.055296678096055984,
375
+ 0.02399350143969059,
376
+ -0.08425548672676086,
377
+ -0.03247550129890442,
378
+ 0.0076597644947469234,
379
+ -0.06612659245729446,
380
+ 0.0009295226191170514,
381
+ 0.10263608396053314,
382
+ 0.07443418353796005,
383
+ 0.01991223357617855,
384
+ -0.019950730726122856,
385
+ -0.0030020412523299456,
386
+ 0.09624635428190231,
387
+ 0.06115877628326416,
388
+ -0.09458866715431213,
389
+ -0.008059244602918625,
390
+ 0.05025295913219452,
391
+ -0.10532546043395996,
392
+ 0.06978560239076614
393
+ ],
394
+ "importance": 0.5,
395
+ "relevance_score": 3.4028234663852886e+38
396
+ },
397
+ {
398
+ "id": 2,
399
+ "content": "User mentioned: User shared their name. Details: my name is edwin",
400
+ "context": "During conversation at 2026-01-09 22:26:39",
401
+ "type": "conversation",
402
+ "timestamp": "2026-01-09T22:26:39.513887",
403
+ "embedding": [
404
+ -0.05643876641988754,
405
+ 0.006340052932500839,
406
+ -0.0825352817773819,
407
+ -0.007329378742724657,
408
+ -0.05459514632821083,
409
+ 0.013580982573330402,
410
+ 0.11820705980062485,
411
+ 0.010445385240018368,
412
+ 0.0011700979666784406,
413
+ -0.060769662261009216,
414
+ -0.0022343441378325224,
415
+ -0.01490565575659275,
416
+ 0.048100657761096954,
417
+ -0.014894277788698673,
418
+ -0.03501866012811661,
419
+ 0.0377735011279583,
420
+ 0.0013687534956261516,
421
+ -0.009943850338459015,
422
+ -0.07332146167755127,
423
+ -0.08760516345500946,
424
+ -0.0757228210568428,
425
+ 0.016015511006116867,
426
+ -0.041063662618398666,
427
+ -0.01715191639959812,
428
+ 0.09080062061548233,
429
+ 0.029597856104373932,
430
+ 0.008221178315579891,
431
+ 0.08211426436901093,
432
+ -0.03264711797237396,
433
+ 0.025607872754335403,
434
+ 0.02878875844180584,
435
+ -0.03647315874695778,
436
+ 0.06389915198087692,
437
+ 0.06119699031114578,
438
+ -0.06896678358316422,
439
+ -0.06345822662115097,
440
+ -0.11721869558095932,
441
+ -0.008107546716928482,
442
+ 0.030358554795384407,
443
+ -0.08242306858301163,
444
+ -0.007212796248495579,
445
+ -0.03161206841468811,
446
+ -0.00012109880481148139,
447
+ 0.049195464700460434,
448
+ -0.08571715652942657,
449
+ 0.11025681346654892,
450
+ 0.004261036869138479,
451
+ 0.03962382674217224,
452
+ 0.024767208844423294,
453
+ 0.09271345287561417,
454
+ -0.05902561917901039,
455
+ -0.03769134730100632,
456
+ 0.02065889537334442,
457
+ 0.0032142195850610733,
458
+ -0.006228269077837467,
459
+ -0.025914793834090233,
460
+ 0.0007751010707579553,
461
+ 0.04010569304227829,
462
+ -0.03272290900349617,
463
+ 0.002311297692358494,
464
+ -0.02982933074235916,
465
+ 0.00692555820569396,
466
+ -0.015722505748271942,
467
+ 0.02992244064807892,
468
+ -0.021927468478679657,
469
+ -0.014504549093544483,
470
+ -0.038329508155584335,
471
+ -0.03579073026776314,
472
+ 0.07539373636245728,
473
+ -0.05879088491201401,
474
+ 0.01757119782269001,
475
+ 0.07439084351062775,
476
+ -0.021343529224395752,
477
+ -0.0060766832903027534,
478
+ 0.009848019108176231,
479
+ 0.024815808981657028,
480
+ -0.014892222359776497,
481
+ 0.025040600448846817,
482
+ -0.04609399661421776,
483
+ -0.026013556867837906,
484
+ -0.0754813700914383,
485
+ 0.06303617358207703,
486
+ -0.06724913418292999,
487
+ -0.09214217215776443,
488
+ -0.043927520513534546,
489
+ 0.08804777264595032,
490
+ -0.025010058656334877,
491
+ -0.043386854231357574,
492
+ -0.023963088169693947,
493
+ -0.03483190760016441,
494
+ 0.10186033695936203,
495
+ 0.056073036044836044,
496
+ 0.10330173373222351,
497
+ -0.03682665154337883,
498
+ -0.05081573873758316,
499
+ -0.0105367973446846,
500
+ 0.01409026701003313,
501
+ 0.05235733464360237,
502
+ -0.15517717599868774,
503
+ 0.08759670704603195,
504
+ -0.06892723590135574,
505
+ 0.07809031754732132,
506
+ 0.002823751186951995,
507
+ 0.0049567739479243755,
508
+ 0.04152959585189819,
509
+ 0.04690350219607353,
510
+ 0.012146921828389168,
511
+ 0.005614860914647579,
512
+ -0.02754994109272957,
513
+ -0.011704501695930958,
514
+ 0.02488057315349579,
515
+ -0.054516419768333435,
516
+ -0.08275116980075836,
517
+ -0.015179515816271305,
518
+ 0.06472513824701309,
519
+ 0.0029180096462368965,
520
+ -0.009562947787344456,
521
+ 0.02914739027619362,
522
+ 0.02885391376912594,
523
+ 0.0018100666347891092,
524
+ -0.027522297576069832,
525
+ 0.009483659639954567,
526
+ -0.05186343565583229,
527
+ 0.016881249845027924,
528
+ -0.054728783667087555,
529
+ 0.0021105981431901455,
530
+ 0.018439166247844696,
531
+ -3.0879237425903294e-33,
532
+ -0.012961992993950844,
533
+ 0.0596257783472538,
534
+ 0.0385788232088089,
535
+ 0.08194147050380707,
536
+ -0.04683526232838631,
537
+ 0.01699860766530037,
538
+ -0.12882420420646667,
539
+ 0.010512175038456917,
540
+ -0.06750291585922241,
541
+ -0.08365614712238312,
542
+ 0.06760998070240021,
543
+ 0.06317827850580215,
544
+ 0.053511008620262146,
545
+ -0.07711957395076752,
546
+ -0.02098703756928444,
547
+ 0.02011113241314888,
548
+ 0.03377315029501915,
549
+ 0.019801165908575058,
550
+ 0.028557846322655678,
551
+ 0.11588888615369797,
552
+ 0.03532402217388153,
553
+ -0.03663478419184685,
554
+ 0.022024964913725853,
555
+ 0.04794193431735039,
556
+ -0.025263769552111626,
557
+ -0.038302477449178696,
558
+ 0.05644823983311653,
559
+ -0.06020880863070488,
560
+ 0.1417873203754425,
561
+ 0.02940896339714527,
562
+ -0.025076601654291153,
563
+ 0.04585685953497887,
564
+ -0.022619565948843956,
565
+ 0.01040772907435894,
566
+ 0.016547253355383873,
567
+ 0.05253582447767258,
568
+ 0.06759890168905258,
569
+ -0.025432979688048363,
570
+ -0.09293048083782196,
571
+ 0.05766065791249275,
572
+ 0.0553952120244503,
573
+ 0.0060941074043512344,
574
+ -0.0580531470477581,
575
+ -0.029363097622990608,
576
+ -0.12619534134864807,
577
+ 0.0008715441217646003,
578
+ 0.02210158295929432,
579
+ 0.11483465880155563,
580
+ 0.012663383968174458,
581
+ -0.011448797769844532,
582
+ -0.06519268453121185,
583
+ 0.003468132112175226,
584
+ -0.04319766163825989,
585
+ 0.024161361157894135,
586
+ 0.0003276085772085935,
587
+ -0.05301162600517273,
588
+ -0.007179405074566603,
589
+ 0.01400463655591011,
590
+ -0.03051787056028843,
591
+ -0.0337553508579731,
592
+ 0.027168763801455498,
593
+ 0.03457282483577728,
594
+ 0.008677193894982338,
595
+ 0.012068578042089939,
596
+ -0.06278853118419647,
597
+ -0.09913598746061325,
598
+ -0.003426732961088419,
599
+ -0.03781317546963692,
600
+ 0.027403216809034348,
601
+ 0.020420311018824577,
602
+ -0.016337284818291664,
603
+ 0.015417809598147869,
604
+ 0.04849385470151901,
605
+ 0.01005076989531517,
606
+ -0.03850109502673149,
607
+ -0.007422123569995165,
608
+ -0.07312804460525513,
609
+ 0.06765672564506531,
610
+ -0.019966645166277885,
611
+ 0.04609200358390808,
612
+ -0.015026352368295193,
613
+ -0.03275790065526962,
614
+ -0.04104631394147873,
615
+ -0.022550813853740692,
616
+ -0.09472212195396423,
617
+ 0.06362135708332062,
618
+ -0.09414522349834442,
619
+ 0.015337715856730938,
620
+ -0.10672953724861145,
621
+ 0.02225402370095253,
622
+ 0.013498932123184204,
623
+ 0.09225743263959885,
624
+ 0.07570606470108032,
625
+ 0.0995408445596695,
626
+ -0.03965884447097778,
627
+ -6.573768485981327e-34,
628
+ -0.07139831781387329,
629
+ -0.009486247785389423,
630
+ -0.03551442176103592,
631
+ -0.05034289509057999,
632
+ 0.08578179031610489,
633
+ -0.05234121158719063,
634
+ -0.03845597803592682,
635
+ 0.058435436338186264,
636
+ -0.05663018673658371,
637
+ 0.024962928146123886,
638
+ 0.035042550414800644,
639
+ -0.0068955980241298676,
640
+ 0.0008154893876053393,
641
+ -0.028416849672794342,
642
+ 0.015835579484701157,
643
+ 0.004946228116750717,
644
+ 0.0798116996884346,
645
+ 0.04050973802804947,
646
+ -0.010325375013053417,
647
+ -0.043313220143318176,
648
+ -0.05247000977396965,
649
+ 0.06197315454483032,
650
+ -0.049068648368120193,
651
+ -0.03643595427274704,
652
+ 0.010386759415268898,
653
+ -0.03060474991798401,
654
+ 0.07041051238775253,
655
+ -0.010620801709592342,
656
+ -0.0018937480635941029,
657
+ -0.040896959602832794,
658
+ 0.024643540382385254,
659
+ 0.03827774152159691,
660
+ -0.12103264033794403,
661
+ -0.09143630415201187,
662
+ -0.08608811348676682,
663
+ 0.012372898869216442,
664
+ -0.01163309346884489,
665
+ 0.08217961341142654,
666
+ -0.006975108757615089,
667
+ -0.033556047827005386,
668
+ 0.015503179281949997,
669
+ 0.07439612597227097,
670
+ 0.01514509879052639,
671
+ 0.02855636551976204,
672
+ -0.05927750840783119,
673
+ -0.04735465347766876,
674
+ -0.03468931466341019,
675
+ -0.07146055996417999,
676
+ 0.02044123411178589,
677
+ 0.0860150158405304,
678
+ 0.009616846218705177,
679
+ -0.09097566455602646,
680
+ 0.04584784433245659,
681
+ -0.09588448703289032,
682
+ -0.012232123874127865,
683
+ -0.0003395208332221955,
684
+ 0.08498546481132507,
685
+ -0.011024896055459976,
686
+ 0.09244536608457565,
687
+ 0.00946288462728262,
688
+ -0.0763309970498085,
689
+ 0.011293893679976463,
690
+ -0.04752162843942642,
691
+ 0.11801411956548691,
692
+ 0.02423446998000145,
693
+ -0.031438689678907394,
694
+ 0.004808045923709869,
695
+ 0.05994592234492302,
696
+ 0.020935019478201866,
697
+ -0.03998388350009918,
698
+ 0.09672801196575165,
699
+ -0.05240225791931152,
700
+ 0.02402358688414097,
701
+ 0.008902295492589474,
702
+ 0.016130104660987854,
703
+ 0.018190735951066017,
704
+ 0.02256973460316658,
705
+ -0.004295494873076677,
706
+ -0.020879359915852547,
707
+ 0.06166696920990944,
708
+ 0.02340847998857498,
709
+ 0.04847263917326927,
710
+ 0.007622626144438982,
711
+ 0.045097313821315765,
712
+ -0.02581077069044113,
713
+ -0.06806942820549011,
714
+ 0.04291797801852226,
715
+ 0.05493941903114319,
716
+ -0.017246540635824203,
717
+ 0.040700968354940414,
718
+ 0.03668623045086861,
719
+ -0.036395397037267685,
720
+ -0.039607174694538116,
721
+ -0.0674767717719078,
722
+ -0.02262483909726143,
723
+ -1.983555719675678e-08,
724
+ -0.01725439541041851,
725
+ -0.023210182785987854,
726
+ 0.0214429572224617,
727
+ 0.08773590624332428,
728
+ 0.02890642359852791,
729
+ 0.05008307844400406,
730
+ 0.0386715866625309,
731
+ 0.05411011353135109,
732
+ -0.030319014564156532,
733
+ 0.06525710225105286,
734
+ -0.034479085355997086,
735
+ 0.021844418719410896,
736
+ -0.029367344453930855,
737
+ 0.025703189894557,
738
+ 0.10176338255405426,
739
+ -0.07165675610303879,
740
+ -0.007929731160402298,
741
+ 0.03543964773416519,
742
+ -0.03774898499250412,
743
+ -0.06231209263205528,
744
+ -0.047276586294174194,
745
+ -0.029912583529949188,
746
+ 0.014294497668743134,
747
+ -0.08385027199983597,
748
+ -0.000271238706773147,
749
+ 0.006358132231980562,
750
+ 0.014557887800037861,
751
+ 0.010368247516453266,
752
+ -0.04932534322142601,
753
+ -0.03402839973568916,
754
+ -0.04656204581260681,
755
+ 0.07528579980134964,
756
+ 0.05115582421422005,
757
+ -0.0008488013409078121,
758
+ -0.04342127963900566,
759
+ 0.0033140804152935743,
760
+ 0.002237041015177965,
761
+ 0.008954676799476147,
762
+ -0.020682206377387047,
763
+ -0.012842242605984211,
764
+ -0.060310740023851395,
765
+ 0.015884054824709892,
766
+ 0.03775676712393761,
767
+ 0.015396155416965485,
768
+ 0.08170188218355179,
769
+ 0.07413624972105026,
770
+ 0.018573077395558357,
771
+ -0.07058368623256683,
772
+ -0.006621289532631636,
773
+ -0.0138900401070714,
774
+ -0.06558379530906677,
775
+ -0.011528769508004189,
776
+ 0.09618879854679108,
777
+ 0.07202176004648209,
778
+ 0.0008702993509359658,
779
+ -0.01355170551687479,
780
+ -0.008986256085336208,
781
+ 0.0859515517950058,
782
+ 0.05258339270949364,
783
+ -0.09769712388515472,
784
+ 0.004891761112958193,
785
+ 0.03664194419980049,
786
+ -0.10887455940246582,
787
+ 0.09263604134321213
788
+ ],
789
+ "importance": 0.5
790
+ }
791
+ ]
memories/timeline.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Memory Timeline
2
+
3
+ ## 2026-01-09
4
+
5
+ - **Conversation** (22:26:39): User mentioned: User shared their name. Details: my name is edwin
6
+ - **Conversation** (22:25:17): User mentioned: User shared their name. Details: hello my name is edwin mauricio
7
+
memory-chat-space.zip ADDED
Binary file (8.98 kB). View file
 
memory_manager.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import time
4
+ from typing import List, Dict, Optional, Tuple
5
+ from datetime import datetime
6
+ from sentence_transformers import SentenceTransformer
7
+ import faiss
8
+ import numpy as np
9
+ from rich.console import Console
10
+
11
+ console = Console()
12
+
13
+ class MemoryManager:
14
+ """Manages user memories using vector embeddings and FAISS for efficient retrieval."""
15
+
16
+ def __init__(self, memory_dir: str = "memories"):
17
+ """
18
+ Initialize the memory manager.
19
+
20
+ Args:
21
+ memory_dir: Directory to store memory files
22
+ """
23
+ self.memory_dir = memory_dir
24
+ self.memories_file = os.path.join(memory_dir, "memories.json")
25
+ self.timeline_file = os.path.join(memory_dir, "timeline.md")
26
+
27
+ # Create memory directory if it doesn't exist
28
+ os.makedirs(memory_dir, exist_ok=True)
29
+
30
+ # Initialize sentence transformer for embeddings
31
+ self.embedder = SentenceTransformer('all-MiniLM-L6-v2')
32
+
33
+ # Load existing memories or create empty list
34
+ self.memories = self._load_memories()
35
+
36
+ # Initialize FAISS index
37
+ self.dimension = 384 # Dimension of MiniLM embeddings
38
+ self.index = faiss.IndexFlatL2(self.dimension)
39
+ self._build_index()
40
+
41
+ def _load_memories(self) -> List[Dict]:
42
+ """Load memories from JSON file."""
43
+ if os.path.exists(self.memories_file):
44
+ try:
45
+ with open(self.memories_file, 'r') as f:
46
+ return json.load(f)
47
+ except Exception as e:
48
+ console.print(f"[red]Error loading memories: {e}[/red]")
49
+ return []
50
+ return []
51
+
52
+ def _save_memories(self):
53
+ """Save memories to JSON file."""
54
+ try:
55
+ with open(self.memories_file, 'w') as f:
56
+ json.dump(self.memories, f, indent=2)
57
+ except Exception as e:
58
+ console.print(f"[red]Error saving memories: {e}[/red]")
59
+
60
+ def _build_index(self):
61
+ """Build FAISS index from existing memories."""
62
+ if self.memories:
63
+ embeddings = []
64
+ for memory in self.memories:
65
+ if 'embedding' in memory:
66
+ embeddings.append(np.array(memory['embedding'], dtype='float32'))
67
+
68
+ if embeddings:
69
+ embeddings = np.array(embeddings)
70
+ self.index.add(embeddings)
71
+
72
+ def add_memory(self, content: str, context: str = "", memory_type: str = "general") -> Dict:
73
+ """
74
+ Add a new memory to the memory store.
75
+
76
+ Args:
77
+ content: The main content of the memory
78
+ context: Additional context about when/where this occurred
79
+ memory_type: Type of memory (general, fact, preference, etc.)
80
+
81
+ Returns:
82
+ The created memory object
83
+ """
84
+ # Create embedding for the memory
85
+ embedding = self.embedder.encode(content).astype('float32')
86
+
87
+ # Create memory object
88
+ memory = {
89
+ "id": len(self.memories) + 1,
90
+ "content": content,
91
+ "context": context,
92
+ "type": memory_type,
93
+ "timestamp": datetime.now().isoformat(),
94
+ "embedding": embedding.tolist(),
95
+ "importance": self._calculate_importance(content)
96
+ }
97
+
98
+ # Add to memories list
99
+ self.memories.append(memory)
100
+
101
+ # Add to FAISS index
102
+ self.index.add(embedding.reshape(1, -1))
103
+
104
+ # Save to file
105
+ self._save_memories()
106
+
107
+ # Update timeline
108
+ self._update_timeline()
109
+
110
+ console.print(f"[green]✓ Memory added: {content[:50]}...[/green]")
111
+ return memory
112
+
113
+ def _calculate_importance(self, content: str) -> float:
114
+ """
115
+ Calculate the importance score of a memory based on its content.
116
+
117
+ Args:
118
+ content: The memory content
119
+
120
+ Returns:
121
+ Importance score between 0 and 1
122
+ """
123
+ # Simple importance calculation based on content length and keywords
124
+ importance = 0.5 # Base importance
125
+
126
+ # Keywords that indicate higher importance
127
+ important_keywords = [
128
+ "love", "family", "important", "urgent", "must", "remember",
129
+ "birthday", "anniversary", "special", "favorite", "hate",
130
+ "never", "always", "often", "every", "daily", "weekly"
131
+ ]
132
+
133
+ content_lower = content.lower()
134
+ for keyword in important_keywords:
135
+ if keyword in content_lower:
136
+ importance += 0.1
137
+
138
+ # Longer memories might be more important
139
+ if len(content) > 100:
140
+ importance += 0.1
141
+
142
+ return min(importance, 1.0)
143
+
144
+ def retrieve_memories(self, query: str, k: int = 5) -> List[Dict]:
145
+ """
146
+ Retrieve relevant memories based on a query.
147
+
148
+ Args:
149
+ query: The search query
150
+ k: Number of memories to retrieve
151
+
152
+ Returns:
153
+ List of relevant memories sorted by relevance
154
+ """
155
+ if not self.memories:
156
+ return []
157
+
158
+ # Create embedding for the query
159
+ query_embedding = self.embedder.encode(query).astype('float32')
160
+
161
+ # Search in FAISS index
162
+ distances, indices = self.index.search(query_embedding.reshape(1, -1), k)
163
+
164
+ # Get the memories
165
+ relevant_memories = []
166
+ for i, idx in enumerate(indices[0]):
167
+ if idx < len(self.memories):
168
+ memory = self.memories[idx]
169
+ memory['relevance_score'] = float(distances[0][i])
170
+ relevant_memories.append(memory)
171
+
172
+ # Sort by relevance (lower distance = more relevant)
173
+ relevant_memories.sort(key=lambda x: x['relevance_score'])
174
+
175
+ return relevant_memories
176
+
177
+ def get_recent_memories(self, limit: int = 10) -> List[Dict]:
178
+ """Get the most recent memories."""
179
+ return sorted(self.memories, key=lambda x: x['timestamp'], reverse=True)[:limit]
180
+
181
+ def get_memory_types(self) -> Dict[str, int]:
182
+ """Get statistics about memory types."""
183
+ type_counts = {}
184
+ for memory in self.memories:
185
+ memory_type = memory.get('type', 'general')
186
+ type_counts[memory_type] = type_counts.get(memory_type, 0) + 1
187
+ return type_counts
188
+
189
+ def _update_timeline(self):
190
+ """Update the human-readable timeline file."""
191
+ timeline_content = "# Memory Timeline\n\n"
192
+
193
+ # Group memories by date
194
+ memories_by_date = {}
195
+ for memory in sorted(self.memories, key=lambda x: x['timestamp'], reverse=True):
196
+ date = memory['timestamp'][:10] # YYYY-MM-DD
197
+ if date not in memories_by_date:
198
+ memories_by_date[date] = []
199
+ memories_by_date[date].append(memory)
200
+
201
+ # Build timeline
202
+ for date in sorted(memories_by_date.keys(), reverse=True):
203
+ timeline_content += f"## {date}\n\n"
204
+ for memory in memories_by_date[date]:
205
+ timeline_content += f"- **{memory['type'].title()}** ({memory['timestamp'][11:19]}): {memory['content']}\n"
206
+ timeline_content += "\n"
207
+
208
+ try:
209
+ with open(self.timeline_file, 'w') as f:
210
+ f.write(timeline_content)
211
+ except Exception as e:
212
+ console.print(f"[red]Error updating timeline: {e}[/red]")
213
+
214
+ def get_summary(self) -> Dict:
215
+ """Get a summary of the memory store."""
216
+ return {
217
+ "total_memories": len(self.memories),
218
+ "memory_types": self.get_memory_types(),
219
+ "recent_memories": self.get_recent_memories(5),
220
+ "timeline_file": self.timeline_file
221
+ }
222
+
223
+ def clear_memories(self):
224
+ """Clear all memories."""
225
+ self.memories = []
226
+ self.index = faiss.IndexFlatL2(self.dimension)
227
+ self._save_memories()
228
+ self._update_timeline()
229
+ console.print("[yellow]All memories cleared.[/yellow]")
quick_git_deploy.sh ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Quick Git Deployment to Hugging Face Spaces
4
+ # Run this script to deploy your Memory Chat application
5
+
6
+ echo "🚀 Memory Chat - Quick Git Deployment to Hugging Face Spaces"
7
+ echo "=============================================================="
8
+
9
+ # Check if git is installed
10
+ if ! command -v git &> /dev/null; then
11
+ echo "❌ Git is not installed. Please install Git first."
12
+ exit 1
13
+ fi
14
+
15
+ # Check if required files exist
16
+ required_files=("app.py" "memory_manager.py" "chat_interface.py" "config.py" "requirements.txt" "README.md")
17
+ for file in "${required_files[@]}"; do
18
+ if [ ! -f "$file" ]; then
19
+ echo "❌ Missing file: $file"
20
+ echo "Please ensure all required files are in the current directory."
21
+ exit 1
22
+ fi
23
+ done
24
+
25
+ echo "✅ All required files found"
26
+
27
+ # Get user input
28
+ read -p "Enter your Hugging Face username: " username
29
+ read -p "Enter your Space name (e.g., memory-chat): " space_name
30
+
31
+ # Check if this is a new Space or existing
32
+ echo ""
33
+ echo "Is this a new Space? (y/n)"
34
+ read -p "Choice [y/n]: " new_space
35
+
36
+ if [ "$new_space" = "y" ] || [ "$new_space" = "Y" ]; then
37
+ echo ""
38
+ echo "🌐 Creating new Space..."
39
+ echo "Please create your Space at: https://huggingface.co/spaces/new"
40
+ echo ""
41
+ echo "Space details:"
42
+ echo "- Name: $space_name"
43
+ echo "- Type: Gradio"
44
+ echo "- Visibility: Public"
45
+ echo ""
46
+ echo "After creating the Space, press Enter to continue..."
47
+ read
48
+ fi
49
+
50
+ # Setup Git
51
+ echo ""
52
+ echo "🔧 Setting up Git repository..."
53
+
54
+ # Initialize if not already
55
+ if [ ! -d ".git" ]; then
56
+ git init
57
+ fi
58
+
59
+ # Get Hugging Face token
60
+ echo ""
61
+ echo "🔐 Getting Hugging Face credentials..."
62
+ echo "Please get your Hugging Face API token:"
63
+ echo "1. Go to: https://huggingface.co/settings/tokens"
64
+ echo "2. Click 'New token'"
65
+ echo "3. Set name: 'spaces-deploy'"
66
+ echo "4. Set role: 'write'"
67
+ echo "5. Copy the token"
68
+ echo ""
69
+ read -s -p "Enter your Hugging Face API token: " hf_token
70
+ echo ""
71
+
72
+ # Setup remote URL
73
+ remote_url="https://$username:$hf_token@huggingface.co/spaces/$username/$space_name"
74
+
75
+ # Remove existing remote if exists
76
+ git remote remove origin 2>/dev/null || true
77
+
78
+ # Add remote
79
+ git remote add origin "$remote_url"
80
+ echo "✅ Git remote configured"
81
+
82
+ # Add files and commit
83
+ echo ""
84
+ echo "📁 Preparing files..."
85
+ git add .
86
+ git commit -m "Initial commit: Memory Chat application"
87
+ echo "✅ Files committed"
88
+
89
+ # Push to Hugging Face
90
+ echo ""
91
+ echo "🚀 Deploying to Hugging Face Spaces..."
92
+ if git push -u origin main; then
93
+ echo ""
94
+ echo "🎉 Successfully deployed!"
95
+ echo "🌐 Your Space: https://huggingface.co/spaces/$username/$space_name"
96
+ echo ""
97
+ echo "💡 Check the 'Logs' tab in your Space for build progress."
98
+ echo "💡 Your Space should be live in 3-5 minutes."
99
+ else
100
+ echo "❌ Deployment failed. Trying force push..."
101
+ if git push -u origin main --force; then
102
+ echo ""
103
+ echo "🎉 Successfully deployed (force push)!"
104
+ echo "🌐 Your Space: https://huggingface.co/spaces/$username/$space_name"
105
+ else
106
+ echo "❌ Failed to deploy. Please check your credentials and try again."
107
+ exit 1
108
+ fi
109
+ fi
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core dependencies
2
+ torch>=2.0.0
3
+ transformers>=4.30.0
4
+ gradio>=3.50.0
5
+ langchain>=0.0.300
6
+
7
+ # Memory and data processing
8
+ faiss-cpu>=1.7.0
9
+ sentence-transformers>=2.2.0
10
+ numpy>=1.21.0
11
+ pandas>=1.5.0
12
+
13
+ # Utilities
14
+ python-dotenv>=1.0.0
15
+ rich>=13.0.0
space_app.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hugging Face Spaces version of the Memory Chat application.
3
+ Optimized for the HF Spaces environment with persistent storage.
4
+ """
5
+
6
+ import os
7
+ import gradio as gr
8
+ from memory_manager import MemoryManager
9
+ from chat_interface import HuggingFaceChat
10
+ from rich.console import Console
11
+
12
+ console = Console()
13
+
14
+ class HFSpaceApp:
15
+ """Hugging Face Spaces version of the Memory Chat application."""
16
+
17
+ def __init__(self):
18
+ """Initialize the Spaces application."""
19
+ # Use persistent storage on HF Spaces
20
+ self.memory_dir = "/tmp/memories" if os.getenv("SPACE_ID") else "memories"
21
+ os.makedirs(self.memory_dir, exist_ok=True)
22
+
23
+ self.memory_manager = MemoryManager(self.memory_dir)
24
+ self.chat_interface = HuggingFaceChat()
25
+
26
+ # Conversation history
27
+ self.conversation_history = []
28
+
29
+ # Load existing memories
30
+ summary = self.memory_manager.get_summary()
31
+ console.print(f"[blue]Loaded {summary['total_memories']} memories[/blue]")
32
+
33
+ def should_record_memory(self, user_input: str, ai_response: str) -> bool:
34
+ """Determine if the conversation should be recorded as a memory."""
35
+ important_keywords = [
36
+ "remember", "important", "note", "fact", "detail", "information",
37
+ "love", "hate", "like", "dislike", "favorite", "never", "always",
38
+ "birthday", "anniversary", "special", "urgent", "must", "should"
39
+ ]
40
+
41
+ combined_text = f"{user_input} {ai_response}".lower()
42
+
43
+ for keyword in important_keywords:
44
+ if keyword in combined_text:
45
+ return True
46
+
47
+ personal_patterns = [
48
+ "my name is", "i live in", "i work at", "i study", "my birthday",
49
+ "my favorite", "i love", "i hate", "i like", "i dislike"
50
+ ]
51
+
52
+ for pattern in personal_patterns:
53
+ if pattern in combined_text:
54
+ return True
55
+
56
+ return False
57
+
58
+ def extract_memory_content(self, user_input: str, ai_response: str) -> str:
59
+ """Extract the most important information to store as a memory."""
60
+ if any(word in user_input.lower() for word in ["remember", "note", "save"]):
61
+ return user_input
62
+
63
+ personal_info = []
64
+ if "my name is" in user_input.lower():
65
+ personal_info.append("User shared their name")
66
+ if "i live in" in user_input.lower():
67
+ personal_info.append("User shared their location")
68
+ if "i work at" in user_input.lower():
69
+ personal_info.append("User shared their workplace")
70
+ if "i study" in user_input.lower():
71
+ personal_info.append("User shared their studies")
72
+ if "my birthday" in user_input.lower():
73
+ personal_info.append("User shared their birthday")
74
+ if "my favorite" in user_input.lower():
75
+ personal_info.append("User shared a favorite thing")
76
+
77
+ if personal_info:
78
+ return f"User mentioned: {', '.join(personal_info)}. Details: {user_input}"
79
+
80
+ return user_input
81
+
82
+ def chat_with_memory(self, user_input: str) -> str:
83
+ """Chat with the AI while managing memories."""
84
+ if not self.chat_interface.check_model_availability():
85
+ return "I'm sorry, but I couldn't load the AI model. Please check your internet connection."
86
+
87
+ self.conversation_history.append({"role": "user", "content": user_input})
88
+
89
+ relevant_memories = self.memory_manager.retrieve_memories(user_input, k=3)
90
+
91
+ context = ""
92
+ if relevant_memories:
93
+ context = "Relevant memories:\n"
94
+ for memory in relevant_memories[:2]:
95
+ context += f"- {memory['content']}\n"
96
+ context += "\n"
97
+
98
+ prompt = self.build_prompt(user_input, context)
99
+ ai_response = self.chat_interface.generate_response(prompt)
100
+
101
+ self.conversation_history.append({"role": "assistant", "content": ai_response})
102
+
103
+ if self.should_record_memory(user_input, ai_response):
104
+ memory_content = self.extract_memory_content(user_input, ai_response)
105
+ context_info = f"During conversation at {self.get_current_time()}"
106
+
107
+ self.memory_manager.add_memory(
108
+ content=memory_content,
109
+ context=context_info,
110
+ memory_type="conversation"
111
+ )
112
+
113
+ return ai_response
114
+
115
+ def build_prompt(self, user_input: str, context: str) -> str:
116
+ """Build the prompt for the AI model."""
117
+ prompt = f"{context}Human: {user_input}\nAI: "
118
+ return prompt
119
+
120
+ def get_current_time(self) -> str:
121
+ """Get current time in a readable format."""
122
+ import datetime
123
+ return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
124
+
125
+ def get_memories_summary(self) -> str:
126
+ """Get a summary of stored memories."""
127
+ summary = self.memory_manager.get_summary()
128
+ memory_types = summary['memory_types']
129
+
130
+ summary_text = f"""
131
+ ## Memory Summary
132
+
133
+ **Total Memories:** {summary['total_memories']}
134
+
135
+ **Memory Types:**
136
+ """
137
+ for memory_type, count in memory_types.items():
138
+ summary_text += f"- {memory_type}: {count}\n"
139
+
140
+ return summary_text
141
+
142
+ def get_recent_memories(self) -> str:
143
+ """Get the most recent memories."""
144
+ recent_memories = self.memory_manager.get_recent_memories()
145
+ if not recent_memories:
146
+ return "No memories stored yet."
147
+
148
+ memory_text = "## Recent Memories\n\n"
149
+ for memory in recent_memories:
150
+ memory_text += f"**{memory['type'].title()}** ({memory['timestamp'][:19]}):\n"
151
+ memory_text += f"{memory['content']}\n\n"
152
+
153
+ return memory_text
154
+
155
+ def clear_all_memories(self) -> str:
156
+ """Clear all memories."""
157
+ self.memory_manager.clear_memories()
158
+ return "All memories have been cleared."
159
+
160
+ def get_model_info(self) -> str:
161
+ """Get information about the AI model."""
162
+ info = self.chat_interface.get_model_info()
163
+ return f"""
164
+ ## Model Information
165
+
166
+ **Model:** {info['model_name']}
167
+ **Device:** {info['device']}
168
+ **Available:** {'Yes' if info['available'] else 'No'}
169
+ """
170
+
171
+ def run_gradio_interface(self):
172
+ """Run the Gradio interface optimized for HF Spaces."""
173
+ # Custom CSS for better appearance on Spaces
174
+ css = """
175
+ .gradio-container {
176
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
177
+ }
178
+ .gr-prose h1 {
179
+ text-align: center;
180
+ color: #1f2937;
181
+ }
182
+ .gr-prose h2 {
183
+ color: #374151;
184
+ }
185
+ """
186
+
187
+ with gr.Blocks(title="Memory Chat - Hugging Face Spaces", css=css, theme=gr.themes.Soft()) as demo:
188
+ gr.Markdown("# 🤖 Memory Chat with Hugging Face")
189
+ gr.Markdown("### Chat with an AI that remembers important details about you!")
190
+
191
+ with gr.Tab("💬 Chat"):
192
+ chatbot = gr.Chatbot(height=500)
193
+ with gr.Row():
194
+ msg = gr.Textbox(
195
+ label="Your Message",
196
+ placeholder="Type your message here...",
197
+ scale=4
198
+ )
199
+ submit_btn = gr.Button("Send", scale=1)
200
+
201
+ with gr.Row():
202
+ clear_btn = gr.Button("Clear Conversation")
203
+ clear_memories_btn = gr.Button("Clear All Memories", variant="stop")
204
+
205
+ # Submit on Enter key
206
+ msg.submit(
207
+ fn=self.user,
208
+ inputs=[msg, chatbot],
209
+ outputs=[msg, chatbot],
210
+ queue=False
211
+ )
212
+
213
+ submit_btn.click(
214
+ fn=self.user,
215
+ inputs=[msg, chatbot],
216
+ outputs=[msg, chatbot],
217
+ queue=False
218
+ )
219
+
220
+ clear_btn.click(
221
+ fn=self.clear_history,
222
+ inputs=None,
223
+ outputs=chatbot,
224
+ queue=False
225
+ )
226
+
227
+ clear_memories_btn.click(
228
+ fn=lambda: (self.clear_all_memories(), None),
229
+ inputs=None,
230
+ outputs=[gr.Textbox(), chatbot],
231
+ queue=False
232
+ )
233
+
234
+ with gr.Tab("📚 Memories"):
235
+ memories_summary = gr.Markdown(value=self.get_memories_summary())
236
+ recent_memories = gr.Markdown(value=self.get_recent_memories())
237
+
238
+ with gr.Row():
239
+ refresh_btn = gr.Button("Refresh Memories")
240
+ timeline_link = gr.Markdown(f"[View Timeline]({self.memory_manager.timeline_file})")
241
+
242
+ refresh_btn.click(
243
+ fn=lambda: (self.get_memories_summary(), self.get_recent_memories()),
244
+ inputs=None,
245
+ outputs=[memories_summary, recent_memories],
246
+ queue=False
247
+ )
248
+
249
+ with gr.Tab("🤖 Model Info"):
250
+ model_info = gr.Markdown(value=self.get_model_info())
251
+
252
+ with gr.Tab("ℹ️ About"):
253
+ gr.Markdown("""
254
+ ## About This Application
255
+
256
+ This application combines Hugging Face AI models with a memory system that records important information from your conversations.
257
+
258
+ ### Features:
259
+ - 🤖 Chat with Hugging Face models
260
+ - 💾 Automatic memory recording
261
+ - 📚 View and manage your memories
262
+ - 🔍 Search through your memories
263
+
264
+ ### How it works:
265
+ 1. Have a conversation with the AI
266
+ 2. The system automatically detects important information
267
+ 3. Important memories are stored and can be recalled in future conversations
268
+ 4. View your memory timeline and statistics
269
+
270
+ ### Memory Types:
271
+ - **General**: General information and facts
272
+ - **Conversation**: Important details from chats
273
+ - **Preferences**: Likes, dislikes, favorites
274
+ - **Important**: Critical information marked as important
275
+
276
+ ---
277
+ **Note**: Memories are stored locally and persist between sessions on this Space.
278
+ """)
279
+
280
+ return demo
281
+
282
+ def user(self, user_message, history):
283
+ """Handle user input and generate AI response."""
284
+ if not user_message.strip():
285
+ return "", history
286
+
287
+ ai_response = self.chat_with_memory(user_message)
288
+
289
+ if history is None:
290
+ history = []
291
+ history.append({"role": "user", "content": user_message})
292
+ history.append({"role": "assistant", "content": ai_response})
293
+
294
+ return "", history
295
+
296
+ def clear_history(self):
297
+ """Clear conversation history."""
298
+ self.conversation_history = []
299
+ return None
300
+
301
+ def clear_all_memories(self) -> str:
302
+ """Clear all memories."""
303
+ self.memory_manager.clear_memories()
304
+ return "All memories have been cleared."
305
+
306
+ def main():
307
+ """Main entry point for HF Spaces."""
308
+ console.print("[green]🚀 Starting Memory Chat Application for HF Spaces...[/green]")
309
+
310
+ # Create and run the application
311
+ app = HFSpaceApp()
312
+
313
+ # Run Gradio interface optimized for Spaces
314
+ demo = app.run_gradio_interface()
315
+ demo.launch(
316
+ server_name="0.0.0.0",
317
+ server_port=int(os.environ.get("PORT", 7860)),
318
+ debug=False,
319
+ show_error=True
320
+ )
321
+
322
+ if __name__ == "__main__":
323
+ main()
space_requirements.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Spaces Requirements
2
+ # Optimized for the Spaces environment
3
+
4
+ # Core dependencies
5
+ torch>=2.0.0
6
+ transformers>=4.30.0
7
+ gradio>=4.0.0
8
+
9
+ # Memory and data processing
10
+ faiss-cpu>=1.7.0
11
+ sentence-transformers>=2.2.0
12
+ numpy>=1.21.0
13
+ pandas>=1.5.0
14
+
15
+ # Utilities
16
+ python-dotenv>=1.0.0
17
+ rich>=13.0.0
18
+
19
+ # Additional dependencies for better Spaces performance
20
+ pillow>=9.0.0
21
+ scikit-learn>=1.0.0
22
+ joblib>=1.0.0
23
+
24
+ # For HF Spaces specific optimizations
25
+ huggingface_hub>=0.15.0
test_app.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test script to verify the Memory Chat application works correctly.
3
+ """
4
+
5
+ import sys
6
+ import os
7
+
8
+ # Add the project directory to the Python path
9
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
10
+
11
+ def test_memory_manager():
12
+ """Test the memory manager functionality."""
13
+ print("Testing Memory Manager...")
14
+
15
+ from memory_manager import MemoryManager
16
+
17
+ # Create a test memory manager
18
+ mm = MemoryManager("test_memories")
19
+
20
+ # Test adding a memory
21
+ memory = mm.add_memory(
22
+ content="I love pizza and hate mushrooms",
23
+ context="Testing memory recording",
24
+ memory_type="preference"
25
+ )
26
+
27
+ print(f"Added memory: {memory['content']}")
28
+ print(f"Memory ID: {memory['id']}")
29
+
30
+ # Test retrieving memories
31
+ relevant = mm.retrieve_memories("What do I like to eat?")
32
+ print(f"Found {len(relevant)} relevant memories")
33
+
34
+ # Test summary
35
+ summary = mm.get_summary()
36
+ print(f"Total memories: {summary['total_memories']}")
37
+ print(f"Memory types: {summary['memory_types']}")
38
+
39
+ # Test timeline
40
+ print(f"Timeline file: {mm.timeline_file}")
41
+
42
+ print("✓ Memory Manager tests passed!")
43
+ return True
44
+
45
+ def test_chat_interface():
46
+ """Test the chat interface functionality."""
47
+ print("\nTesting Chat Interface...")
48
+
49
+ from chat_interface import HuggingFaceChat
50
+
51
+ # Create a test chat interface
52
+ chat = HuggingFaceChat(model_name="microsoft/DialoGPT-small")
53
+
54
+ # Test model info
55
+ info = chat.get_model_info()
56
+ print(f"Model: {info['model_name']}")
57
+ print(f"Device: {info['device']}")
58
+ print(f"Available: {info['available']}")
59
+
60
+ if info['available']:
61
+ # Test generating a response
62
+ response = chat.generate_response("Hello, how are you?", max_length=50)
63
+ print(f"Generated response: {response[:50]}...")
64
+ print("✓ Chat Interface tests passed!")
65
+ else:
66
+ print("⚠ Model not available - skipping response generation test")
67
+
68
+ return True
69
+
70
+ def test_main_app():
71
+ """Test the main application functionality."""
72
+ print("\nTesting Main Application...")
73
+
74
+ from app import MemoryChatApp
75
+
76
+ # Create the main app
77
+ app = MemoryChatApp()
78
+
79
+ # Test memory recording logic
80
+ should_record = app.should_record_memory(
81
+ "Remember that I love pizza and hate mushrooms",
82
+ "I'll remember that you love pizza and hate mushrooms"
83
+ )
84
+ print(f"Should record memory: {should_record}")
85
+
86
+ # Test memory extraction
87
+ content = app.extract_memory_content(
88
+ "My name is John and I live in New York",
89
+ "Nice to meet you, John!"
90
+ )
91
+ print(f"Extracted content: {content}")
92
+
93
+ print("✓ Main Application tests passed!")
94
+ return True
95
+
96
+ def main():
97
+ """Run all tests."""
98
+ print("🧪 Running Memory Chat Application Tests\n")
99
+
100
+ try:
101
+ test_memory_manager()
102
+ test_chat_interface()
103
+ test_main_app()
104
+
105
+ print("\n🎉 All tests passed successfully!")
106
+ print("\nTo run the application, use:")
107
+ print("python app.py")
108
+
109
+ except Exception as e:
110
+ print(f"\n❌ Test failed with error: {e}")
111
+ import traceback
112
+ traceback.print_exc()
113
+ return False
114
+
115
+ if __name__ == "__main__":
116
+ main()
test_memories/memories.json ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "id": 1,
4
+ "content": "I love pizza and hate mushrooms",
5
+ "context": "Testing memory recording",
6
+ "type": "preference",
7
+ "timestamp": "2026-01-09T22:17:32.310198",
8
+ "embedding": [
9
+ 0.03875897452235222,
10
+ 0.05280157923698425,
11
+ -0.0036089224740862846,
12
+ 0.03695211187005043,
13
+ -0.023045089095830917,
14
+ -0.03902852535247803,
15
+ 0.009436762891709805,
16
+ 0.0346154123544693,
17
+ 0.043741531670093536,
18
+ -0.04868815094232559,
19
+ -0.006189689971506596,
20
+ -0.11021631956100464,
21
+ -0.009066620841622353,
22
+ -0.0006522072362713516,
23
+ -0.027590803802013397,
24
+ -0.09565330296754837,
25
+ 0.10817263275384903,
26
+ 0.01229641493409872,
27
+ 0.009932232089340687,
28
+ 0.026499642059206963,
29
+ -0.12098328024148941,
30
+ 0.0022552867885679007,
31
+ 0.012434019707143307,
32
+ 0.055118389427661896,
33
+ -0.002861551707610488,
34
+ 0.03585321083664894,
35
+ 0.05726490169763565,
36
+ -0.005705655552446842,
37
+ -0.09828298538923264,
38
+ -0.07979002594947815,
39
+ -0.024431949481368065,
40
+ 0.04378493130207062,
41
+ 0.03211062401533127,
42
+ 0.02371874824166298,
43
+ 0.006798949558287859,
44
+ 0.027640240266919136,
45
+ 0.044980160892009735,
46
+ -0.021570760756731033,
47
+ 0.010082061402499676,
48
+ -0.01285412348806858,
49
+ 0.006022365763783455,
50
+ -0.016429850831627846,
51
+ 0.10763106495141983,
52
+ -0.03610154241323471,
53
+ -0.04212067276239395,
54
+ -0.020476410165429115,
55
+ -0.05501566454768181,
56
+ -0.04217110574245453,
57
+ 0.08153433352708817,
58
+ -0.0022776515688747168,
59
+ -0.006549549754709005,
60
+ -0.04484741389751434,
61
+ 0.0019414419075474143,
62
+ 0.009914860129356384,
63
+ 0.06342000514268875,
64
+ 0.03797575831413269,
65
+ 0.0017721757758408785,
66
+ 0.07385660707950592,
67
+ 0.030930178239941597,
68
+ 0.005188942886888981,
69
+ -0.05744442343711853,
70
+ -0.028558610007166862,
71
+ -0.02010233886539936,
72
+ 0.022334858775138855,
73
+ -0.03946618363261223,
74
+ 0.017596201971173286,
75
+ 0.013011138886213303,
76
+ -0.034720975905656815,
77
+ -0.11083326488733292,
78
+ 0.029160676524043083,
79
+ -0.06863938271999359,
80
+ 0.14139509201049805,
81
+ 0.04009837657213211,
82
+ 0.0042649307288229465,
83
+ 0.03515723720192909,
84
+ 0.05172161012887955,
85
+ -0.07069050520658493,
86
+ -0.11678112298250198,
87
+ -0.016300832852721214,
88
+ -0.00355102913454175,
89
+ 0.006738871801644564,
90
+ 0.039899792522192,
91
+ -0.07166972756385803,
92
+ -0.03614625334739685,
93
+ 0.007328942883759737,
94
+ -0.04860224947333336,
95
+ -0.036764100193977356,
96
+ 0.0898534506559372,
97
+ -0.007359549403190613,
98
+ -0.037999823689460754,
99
+ 0.04665827751159668,
100
+ 0.016000930219888687,
101
+ -0.015914632007479668,
102
+ 0.03706985339522362,
103
+ -0.1284528225660324,
104
+ -0.007612523157149553,
105
+ 0.04461376368999481,
106
+ -0.017212973907589912,
107
+ -0.0577964149415493,
108
+ 0.02981126308441162,
109
+ 0.043312132358551025,
110
+ 0.0226021446287632,
111
+ 0.0028474382124841213,
112
+ -0.015525512397289276,
113
+ -0.0015342201804742217,
114
+ -0.005015364848077297,
115
+ -0.017388317734003067,
116
+ 0.014934140257537365,
117
+ 0.021618826314806938,
118
+ -0.01472227182239294,
119
+ -0.06851861625909805,
120
+ -0.020711563527584076,
121
+ -0.006072571501135826,
122
+ -0.10369426757097244,
123
+ -0.04529580473899841,
124
+ 0.036348480731248856,
125
+ 0.17342831194400787,
126
+ -0.01117977499961853,
127
+ -0.002181128365918994,
128
+ -0.06905186176300049,
129
+ -0.06843563914299011,
130
+ 0.055621787905693054,
131
+ -0.0016529976855963469,
132
+ 0.013280079700052738,
133
+ -0.00802586693316698,
134
+ -0.03741363435983658,
135
+ -0.05268894508481026,
136
+ -4.075902867227461e-33,
137
+ 0.006541554816067219,
138
+ -0.03750442713499069,
139
+ 0.004569194279611111,
140
+ 0.028262028470635414,
141
+ 0.09822557121515274,
142
+ 0.023845698684453964,
143
+ 0.034406550228595734,
144
+ -0.026209214702248573,
145
+ -0.0019082747166976333,
146
+ -0.048137374222278595,
147
+ -0.04675827547907829,
148
+ -0.014687173999845982,
149
+ -0.09685590118169785,
150
+ 0.04304314777255058,
151
+ 0.0956728532910347,
152
+ -0.03698369860649109,
153
+ 0.01719755493104458,
154
+ -0.01942829042673111,
155
+ -0.03239534795284271,
156
+ 0.005671426188200712,
157
+ -0.03917429968714714,
158
+ -0.052515964955091476,
159
+ 0.004365224856883287,
160
+ 0.07336638122797012,
161
+ 0.023350490257143974,
162
+ -0.00924033671617508,
163
+ 0.006770065054297447,
164
+ -0.06278658658266068,
165
+ -0.07000599056482315,
166
+ 0.027859432622790337,
167
+ 0.047039907425642014,
168
+ 0.07487046718597412,
169
+ -0.03225914016366005,
170
+ 0.03604402393102646,
171
+ 0.06695506721735,
172
+ 0.0010574770858511329,
173
+ -0.02069864422082901,
174
+ 0.04274166002869606,
175
+ -0.04989098757505417,
176
+ 0.004137680400162935,
177
+ -0.00025893194833770394,
178
+ 0.008062557317316532,
179
+ -0.01318787969648838,
180
+ -0.00031607673736289144,
181
+ 0.05711536854505539,
182
+ -0.0007494656601920724,
183
+ 0.060785844922065735,
184
+ 0.05949707329273224,
185
+ 0.024985065683722496,
186
+ 0.01749240607023239,
187
+ 0.043190713971853256,
188
+ 0.0016048630932345986,
189
+ 0.0659165307879448,
190
+ 0.06616315990686417,
191
+ 0.004274787846952677,
192
+ -0.020389487966895103,
193
+ -0.00022031544358469546,
194
+ 0.006546191405504942,
195
+ -0.0802990049123764,
196
+ -0.015048844739794731,
197
+ 0.0018401734996587038,
198
+ 0.17213928699493408,
199
+ -0.005646882578730583,
200
+ 0.029732992872595787,
201
+ -0.06042931601405144,
202
+ 0.023296164348721504,
203
+ -0.054148390889167786,
204
+ 0.01718498207628727,
205
+ -0.012741944752633572,
206
+ -0.023687368258833885,
207
+ 0.06259965151548386,
208
+ -0.029198691248893738,
209
+ -0.035791460424661636,
210
+ -0.006957892794162035,
211
+ -0.027986085042357445,
212
+ -0.04067635536193848,
213
+ -0.027017366141080856,
214
+ -0.02490904927253723,
215
+ 0.001286563347093761,
216
+ -0.04923729971051216,
217
+ 0.12612949311733246,
218
+ -0.06118234619498253,
219
+ 0.025343816727399826,
220
+ -0.09424808621406555,
221
+ -0.050376296043395996,
222
+ 0.018575582653284073,
223
+ 0.040960460901260376,
224
+ -0.08399675786495209,
225
+ 0.06317627429962158,
226
+ -0.008798257447779179,
227
+ -0.02382872812449932,
228
+ -0.10085533559322357,
229
+ 0.06266158074140549,
230
+ -0.005287562496960163,
231
+ -0.07304846495389938,
232
+ 2.6339689464668783e-33,
233
+ 0.02700074017047882,
234
+ -0.03891989216208458,
235
+ 0.0906137153506279,
236
+ 0.002930642571300268,
237
+ -0.05978973209857941,
238
+ -0.03640030324459076,
239
+ -0.08346077799797058,
240
+ -0.03455350920557976,
241
+ 0.010466857813298702,
242
+ -0.018092645332217216,
243
+ -0.010924994945526123,
244
+ -0.0056700324639678,
245
+ 0.009872970171272755,
246
+ 0.004627453163266182,
247
+ 0.039202407002449036,
248
+ 0.023374829441308975,
249
+ 0.007121958304196596,
250
+ 0.03754819184541702,
251
+ 0.002887109061703086,
252
+ -0.048984918743371964,
253
+ -0.06600604206323624,
254
+ 0.024129414930939674,
255
+ -0.10960401594638824,
256
+ 0.09468576312065125,
257
+ 0.010289560072124004,
258
+ 0.036206286400556564,
259
+ 0.03706667199730873,
260
+ 0.03738970682024956,
261
+ -0.005809256341308355,
262
+ -0.014523929916322231,
263
+ -0.026120955124497414,
264
+ 0.04401257634162903,
265
+ -0.06476949155330658,
266
+ -0.09099779278039932,
267
+ 0.026981577277183533,
268
+ 0.007235502824187279,
269
+ -0.09973607957363129,
270
+ -0.010897793807089329,
271
+ 0.046681635081768036,
272
+ -0.007838481105864048,
273
+ -0.06591387838125229,
274
+ 0.002104088431224227,
275
+ 0.034640826284885406,
276
+ 0.07849340885877609,
277
+ 0.019736697897315025,
278
+ 0.03956855088472366,
279
+ 0.06556658446788788,
280
+ -0.07211563736200333,
281
+ -0.01375817134976387,
282
+ -0.003739030798897147,
283
+ -0.07897455245256424,
284
+ 0.011246136389672756,
285
+ 0.01158884260803461,
286
+ 0.014312366023659706,
287
+ 0.0849107950925827,
288
+ -0.0038072494789958,
289
+ -0.019378235563635826,
290
+ 0.021105559542775154,
291
+ -0.027357321232557297,
292
+ -0.15211528539657593,
293
+ -0.06424858421087265,
294
+ 0.045168593525886536,
295
+ -0.05706986039876938,
296
+ 0.09536726027727127,
297
+ 0.06616023927927017,
298
+ 0.034766655415296555,
299
+ 0.01604684814810753,
300
+ -0.10831272602081299,
301
+ 0.009145919233560562,
302
+ 0.014202374964952469,
303
+ 0.013556702062487602,
304
+ 0.014952413737773895,
305
+ -0.022692520171403885,
306
+ 0.045712269842624664,
307
+ -0.03190644457936287,
308
+ -0.11130636185407639,
309
+ -0.0584193654358387,
310
+ 0.09788035601377487,
311
+ -0.02719079703092575,
312
+ 0.033073607832193375,
313
+ 0.04209985211491585,
314
+ -3.836547693936154e-05,
315
+ 0.0006786540616303682,
316
+ 0.017447445541620255,
317
+ -0.016584279015660286,
318
+ -0.05588225647807121,
319
+ 0.014428879134356976,
320
+ -0.005860479082912207,
321
+ -0.1216338574886322,
322
+ 0.042214371263980865,
323
+ 0.031251199543476105,
324
+ 0.06258829683065414,
325
+ -0.00560770696029067,
326
+ 0.009469529613852501,
327
+ 0.13937869668006897,
328
+ -1.4204578846488403e-08,
329
+ 0.08057358860969543,
330
+ -0.046007029712200165,
331
+ -0.033160291612148285,
332
+ -0.030236952006816864,
333
+ 0.0028210626915097237,
334
+ -0.05327284336090088,
335
+ 0.01176622323691845,
336
+ 0.05292908474802971,
337
+ -0.004327722359448671,
338
+ 0.01068241335451603,
339
+ -0.025575213134288788,
340
+ 0.13546429574489594,
341
+ -0.011062612757086754,
342
+ 0.0798792764544487,
343
+ 0.013184454292058945,
344
+ 0.05832760035991669,
345
+ 0.08903287351131439,
346
+ -0.07126083970069885,
347
+ 0.0015069111250340939,
348
+ 0.11210285127162933,
349
+ -0.06859140843153,
350
+ 0.0007342977914959192,
351
+ 0.008753067813813686,
352
+ -0.03712032362818718,
353
+ -0.03303607553243637,
354
+ -0.011919373646378517,
355
+ 0.06076401099562645,
356
+ -0.04716166853904724,
357
+ 0.11556678265333176,
358
+ 0.08400286734104156,
359
+ 0.011252880096435547,
360
+ -0.01946060173213482,
361
+ -0.027820004150271416,
362
+ 0.0015117272268980742,
363
+ 0.0003631317522376776,
364
+ -0.001311573782004416,
365
+ -0.029412981122732162,
366
+ -0.06827309727668762,
367
+ 0.03195794299244881,
368
+ -0.04242730513215065,
369
+ -0.04463118687272072,
370
+ -0.03493130952119827,
371
+ -0.027541792020201683,
372
+ -0.03074466437101364,
373
+ -0.11165875941514969,
374
+ -0.014854801818728447,
375
+ -0.015592128038406372,
376
+ 0.005249170586466789,
377
+ -0.0552591010928154,
378
+ 0.0578744001686573,
379
+ 0.046071503311395645,
380
+ 0.06435728073120117,
381
+ 0.05426222085952759,
382
+ 0.03952239081263542,
383
+ 0.057633351534605026,
384
+ -0.006186990067362785,
385
+ 0.09624188393354416,
386
+ 0.07667811959981918,
387
+ 0.03082921728491783,
388
+ 0.025117972865700722,
389
+ 0.048737410455942154,
390
+ 0.05643203482031822,
391
+ 0.06902598589658737,
392
+ -0.05484015494585037
393
+ ],
394
+ "importance": 0.7
395
+ }
396
+ ]
test_memories/timeline.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Memory Timeline
2
+
3
+ ## 2026-01-09
4
+
5
+ - **Preference** (22:17:32): I love pizza and hate mushrooms
6
+