Spaces:
Runtime error
Runtime error
Commit
·
fadbeb2
1
Parent(s):
7b6b0f6
⚙️ Integrate MongoDB for memory storage and retrieval; add search functionality
Browse files
app.py
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
|
|
| 1 |
from typing import Literal
|
|
|
|
| 2 |
from io import StringIO
|
| 3 |
import datetime
|
| 4 |
import requests
|
|
@@ -6,11 +8,23 @@ import random
|
|
| 6 |
import base64
|
| 7 |
import gradio
|
| 8 |
import qrcode
|
| 9 |
-
import json
|
| 10 |
import sys
|
| 11 |
import os
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
Theme = gradio.themes.Citrus( # type: ignore
|
| 15 |
primary_hue='blue',
|
| 16 |
secondary_hue='blue',
|
|
@@ -175,64 +189,106 @@ def QRCode(Text: str) -> str:
|
|
| 175 |
# ╰────────────────────╯
|
| 176 |
|
| 177 |
def SaveMemory(Text: str) -> str:
|
| 178 |
-
'''Save a memory with the given text.
|
| 179 |
Args:
|
| 180 |
Text (str): The text to save as a memory.
|
| 181 |
Returns:
|
| 182 |
str: A message indicating the result of the save operation.
|
| 183 |
'''
|
| 184 |
try:
|
| 185 |
-
if
|
| 186 |
-
|
| 187 |
-
Memories = json.load(File)
|
| 188 |
-
else:
|
| 189 |
-
Memories = []
|
| 190 |
|
| 191 |
MemoryEntry = {
|
| 192 |
-
'id': len(Memories) + 1,
|
| 193 |
'text': Text,
|
| 194 |
-
'timestamp': datetime.datetime.now()
|
| 195 |
}
|
| 196 |
-
Memories.append(MemoryEntry)
|
| 197 |
-
|
| 198 |
-
with open(MemoryFile, 'w') as File:
|
| 199 |
-
json.dump(Memories, File)
|
| 200 |
|
| 201 |
-
|
|
|
|
| 202 |
except Exception as e:
|
| 203 |
return f'Error saving memory: {str(e)}'
|
| 204 |
|
| 205 |
def ListMemories() -> str:
|
| 206 |
-
'''List all saved memories.
|
| 207 |
Returns:
|
| 208 |
str: A formatted string of all saved memories.
|
| 209 |
'''
|
| 210 |
try:
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
except Exception as e:
|
| 215 |
return f'Error listing memories: {str(e)}'
|
| 216 |
|
| 217 |
-
def DeleteMemory(MemoryID:
|
| 218 |
-
'''Delete a memory by its
|
| 219 |
Args:
|
| 220 |
-
MemoryID (
|
| 221 |
Returns:
|
| 222 |
str: A message indicating the result of the delete operation.
|
| 223 |
'''
|
| 224 |
try:
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
except Exception as e:
|
| 234 |
return f'Error deleting memory: {str(e)}'
|
| 235 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
# ╭──────────────────────────────╮
|
| 237 |
# │ Gradio Interface Setup │
|
| 238 |
# ╰────────────────────────────��─╯
|
|
@@ -302,7 +358,7 @@ with gradio.Blocks(
|
|
| 302 |
ReverseOutput = gradio.Text(label='Reversed Text ↩️', interactive=False)
|
| 303 |
ReverseBtn = gradio.Button('Reverse Text 🔄', variant='primary')
|
| 304 |
ReverseBtn.click(Reverse, inputs=ReverseInput, outputs=ReverseOutput)
|
| 305 |
-
|
| 306 |
with gradio.Group():
|
| 307 |
WordCountInput = gradio.Textbox(label='Text for Word Count 📏', placeholder='Enter text to count words', lines=3)
|
| 308 |
WordCountChoice = gradio.Radio(label='Count Type 🔢', choices=['words', 'characters'], value='words', interactive=True)
|
|
@@ -334,7 +390,7 @@ with gradio.Blocks(
|
|
| 334 |
SaveBtn.click(SaveMemory, inputs=SaveInput, outputs=SaveOutput)
|
| 335 |
|
| 336 |
with gradio.Group():
|
| 337 |
-
DeleteInput = gradio.
|
| 338 |
DeleteOutput = gradio.Text(label='Delete Result ❌', interactive=False)
|
| 339 |
DeleteBtn = gradio.Button('Delete Memory 🗑️', variant='secondary')
|
| 340 |
DeleteBtn.click(DeleteMemory, inputs=DeleteInput, outputs=DeleteOutput)
|
|
@@ -345,6 +401,12 @@ with gradio.Blocks(
|
|
| 345 |
ListBtn = gradio.Button('List Memories 📄', variant='primary')
|
| 346 |
ListBtn.click(ListMemories, outputs=ListOutput)
|
| 347 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
App.launch(
|
| 349 |
mcp_server=True
|
| 350 |
)
|
|
|
|
| 1 |
+
from pymongo import MongoClient
|
| 2 |
from typing import Literal
|
| 3 |
+
from bson import ObjectId
|
| 4 |
from io import StringIO
|
| 5 |
import datetime
|
| 6 |
import requests
|
|
|
|
| 8 |
import base64
|
| 9 |
import gradio
|
| 10 |
import qrcode
|
|
|
|
| 11 |
import sys
|
| 12 |
import os
|
| 13 |
|
| 14 |
+
MongoURI = os.getenv('MONGO_URI')
|
| 15 |
+
DatabaseName = 'MCP-Utilities'
|
| 16 |
+
CollectionName = 'Memories'
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
Client = MongoClient(MongoURI)
|
| 20 |
+
Database = Client[DatabaseName]
|
| 21 |
+
Collection = Database[CollectionName]
|
| 22 |
+
Client.server_info()
|
| 23 |
+
print('Connected to MongoDB successfully.')
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f'Error connecting to MongoDB: {str(e)}')
|
| 26 |
+
Collection = None
|
| 27 |
+
|
| 28 |
Theme = gradio.themes.Citrus( # type: ignore
|
| 29 |
primary_hue='blue',
|
| 30 |
secondary_hue='blue',
|
|
|
|
| 189 |
# ╰────────────────────╯
|
| 190 |
|
| 191 |
def SaveMemory(Text: str) -> str:
|
| 192 |
+
'''Save a memory with the given text to MongoDB.
|
| 193 |
Args:
|
| 194 |
Text (str): The text to save as a memory.
|
| 195 |
Returns:
|
| 196 |
str: A message indicating the result of the save operation.
|
| 197 |
'''
|
| 198 |
try:
|
| 199 |
+
if Collection is None:
|
| 200 |
+
return 'Error: MongoDB connection not available'
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
MemoryEntry = {
|
|
|
|
| 203 |
'text': Text,
|
| 204 |
+
'timestamp': datetime.datetime.now()
|
| 205 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
+
Result = Collection.insert_one(MemoryEntry)
|
| 208 |
+
return f'Memory saved with ID {str(Result.inserted_id)}'
|
| 209 |
except Exception as e:
|
| 210 |
return f'Error saving memory: {str(e)}'
|
| 211 |
|
| 212 |
def ListMemories() -> str:
|
| 213 |
+
'''List all saved memories from MongoDB.
|
| 214 |
Returns:
|
| 215 |
str: A formatted string of all saved memories.
|
| 216 |
'''
|
| 217 |
try:
|
| 218 |
+
if Collection is None:
|
| 219 |
+
return 'Error: MongoDB connection not available'
|
| 220 |
+
|
| 221 |
+
Memories = list(Collection.find().sort('timestamp', -1).limit(50))
|
| 222 |
+
|
| 223 |
+
if not Memories:
|
| 224 |
+
return 'No memories found.'
|
| 225 |
+
|
| 226 |
+
FormattedMemories = []
|
| 227 |
+
for Memory in Memories:
|
| 228 |
+
Timestamp = Memory['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
|
| 229 |
+
MemoryId = str(Memory['_id'])
|
| 230 |
+
FormattedMemories.append(f'ID: {MemoryId} [{Timestamp}]: {Memory["text"]}')
|
| 231 |
+
|
| 232 |
+
return '\n'.join(FormattedMemories)
|
| 233 |
except Exception as e:
|
| 234 |
return f'Error listing memories: {str(e)}'
|
| 235 |
|
| 236 |
+
def DeleteMemory(MemoryID: str) -> str:
|
| 237 |
+
'''Delete a memory by its MongoDB ObjectId.
|
| 238 |
Args:
|
| 239 |
+
MemoryID (str): The MongoDB ObjectId of the memory to delete.
|
| 240 |
Returns:
|
| 241 |
str: A message indicating the result of the delete operation.
|
| 242 |
'''
|
| 243 |
try:
|
| 244 |
+
if Collection is None:
|
| 245 |
+
return 'Error: MongoDB connection not available'
|
| 246 |
+
|
| 247 |
+
if not ObjectId.is_valid(MemoryID):
|
| 248 |
+
return 'Error: Invalid memory ID format'
|
| 249 |
+
|
| 250 |
+
Result = Collection.delete_one({'_id': ObjectId(MemoryID)})
|
| 251 |
+
|
| 252 |
+
if Result.deleted_count > 0:
|
| 253 |
+
return f'Memory with ID {MemoryID} deleted successfully'
|
| 254 |
+
else:
|
| 255 |
+
return f'Memory with ID {MemoryID} not found'
|
| 256 |
except Exception as e:
|
| 257 |
return f'Error deleting memory: {str(e)}'
|
| 258 |
|
| 259 |
+
def SearchMemories(Query: str) -> str:
|
| 260 |
+
'''Search memories by text content.
|
| 261 |
+
Args:
|
| 262 |
+
Query (str): The text to search for in memories.
|
| 263 |
+
Returns:
|
| 264 |
+
str: A formatted string of matching memories.
|
| 265 |
+
'''
|
| 266 |
+
try:
|
| 267 |
+
if Collection is None:
|
| 268 |
+
return 'Error: MongoDB connection not available'
|
| 269 |
+
|
| 270 |
+
try:
|
| 271 |
+
Collection.create_index([("text", "text")])
|
| 272 |
+
except Exception as e:
|
| 273 |
+
print(f'Error creating text index: {str(e)}')
|
| 274 |
+
|
| 275 |
+
Memories = list(Collection.find(
|
| 276 |
+
{'$text': {'$search': Query}}
|
| 277 |
+
).sort('timestamp', -1).limit(20))
|
| 278 |
+
|
| 279 |
+
if not Memories:
|
| 280 |
+
return f'No memories found matching "{Query}"'
|
| 281 |
+
|
| 282 |
+
FormattedMemories = []
|
| 283 |
+
for Memory in Memories:
|
| 284 |
+
Timestamp = Memory['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
|
| 285 |
+
MemoryId = str(Memory['_id'])
|
| 286 |
+
FormattedMemories.append(f'ID: {MemoryId} [{Timestamp}]: {Memory["text"]}')
|
| 287 |
+
|
| 288 |
+
return '\n'.join(FormattedMemories)
|
| 289 |
+
except Exception as e:
|
| 290 |
+
return f'Error searching memories: {str(e)}'
|
| 291 |
+
|
| 292 |
# ╭──────────────────────────────╮
|
| 293 |
# │ Gradio Interface Setup │
|
| 294 |
# ╰────────────────────────────��─╯
|
|
|
|
| 358 |
ReverseOutput = gradio.Text(label='Reversed Text ↩️', interactive=False)
|
| 359 |
ReverseBtn = gradio.Button('Reverse Text 🔄', variant='primary')
|
| 360 |
ReverseBtn.click(Reverse, inputs=ReverseInput, outputs=ReverseOutput)
|
| 361 |
+
|
| 362 |
with gradio.Group():
|
| 363 |
WordCountInput = gradio.Textbox(label='Text for Word Count 📏', placeholder='Enter text to count words', lines=3)
|
| 364 |
WordCountChoice = gradio.Radio(label='Count Type 🔢', choices=['words', 'characters'], value='words', interactive=True)
|
|
|
|
| 390 |
SaveBtn.click(SaveMemory, inputs=SaveInput, outputs=SaveOutput)
|
| 391 |
|
| 392 |
with gradio.Group():
|
| 393 |
+
DeleteInput = gradio.Textbox(label='Memory ID to Delete 🗑️', placeholder='Enter MongoDB ObjectId', lines=1)
|
| 394 |
DeleteOutput = gradio.Text(label='Delete Result ❌', interactive=False)
|
| 395 |
DeleteBtn = gradio.Button('Delete Memory 🗑️', variant='secondary')
|
| 396 |
DeleteBtn.click(DeleteMemory, inputs=DeleteInput, outputs=DeleteOutput)
|
|
|
|
| 401 |
ListBtn = gradio.Button('List Memories 📄', variant='primary')
|
| 402 |
ListBtn.click(ListMemories, outputs=ListOutput)
|
| 403 |
|
| 404 |
+
with gradio.Group():
|
| 405 |
+
SearchInput = gradio.Textbox(label='Search Memories 🔍', placeholder='Enter text to search in memories', lines=3)
|
| 406 |
+
SearchOutput = gradio.Text(label='Search Results 📑', interactive=False)
|
| 407 |
+
SearchBtn = gradio.Button('Search Memories 🔎', variant='primary')
|
| 408 |
+
SearchBtn.click(SearchMemories, inputs=SearchInput, outputs=SearchOutput)
|
| 409 |
+
|
| 410 |
App.launch(
|
| 411 |
mcp_server=True
|
| 412 |
)
|