File size: 8,055 Bytes
5e5e890 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
# Session & Persistent Memory Manager
import json
import os
from datetime import datetime
from typing import Dict, Any, Optional
class MemoryManager:
"""Manages session data and persistent storage for the LinkedIn enhancer"""
def __init__(self, storage_dir: str = "data"):
self.storage_dir = storage_dir
self.session_data = {}
self.persistent_file = os.path.join(storage_dir, "persistent_data.json")
# Create storage directory if it doesn't exist
os.makedirs(storage_dir, exist_ok=True)
# Load existing persistent data
self.persistent_data = self._load_persistent_data()
def store_session(self, profile_url: str, data: Dict[str, Any]) -> None:
"""
Store session data for a specific profile
Args:
profile_url (str): LinkedIn profile URL as key
data (Dict[str, Any]): Session data to store
"""
session_key = self._create_session_key(profile_url)
self.session_data[session_key] = {
'timestamp': datetime.now().isoformat(),
'profile_url': profile_url,
'data': data
}
def get_session(self, profile_url: str) -> Optional[Dict[str, Any]]:
"""
Retrieve session data for a specific profile
Args:
profile_url (str): LinkedIn profile URL
Returns:
Optional[Dict[str, Any]]: Session data if exists
"""
session_key = self._create_session_key(profile_url)
return self.session_data.get(session_key)
def store_persistent(self, key: str, data: Any) -> None:
"""
Store data persistently to disk
Args:
key (str): Storage key
data (Any): Data to store
"""
self.persistent_data[key] = {
'timestamp': datetime.now().isoformat(),
'data': data
}
self._save_persistent_data()
def get_persistent(self, key: str) -> Optional[Any]:
"""
Retrieve persistent data
Args:
key (str): Storage key
Returns:
Optional[Any]: Stored data if exists
"""
stored_item = self.persistent_data.get(key)
return stored_item['data'] if stored_item else None
def store_user_preferences(self, user_id: str, preferences: Dict[str, Any]) -> None:
"""
Store user preferences
Args:
user_id (str): User identifier
preferences (Dict[str, Any]): User preferences
"""
pref_key = f"user_preferences_{user_id}"
self.store_persistent(pref_key, preferences)
def get_user_preferences(self, user_id: str) -> Dict[str, Any]:
"""
Retrieve user preferences
Args:
user_id (str): User identifier
Returns:
Dict[str, Any]: User preferences
"""
pref_key = f"user_preferences_{user_id}"
preferences = self.get_persistent(pref_key)
return preferences if preferences else {}
def store_analysis_history(self, profile_url: str, analysis: Dict[str, Any]) -> None:
"""
Store analysis history for tracking improvements
Args:
profile_url (str): LinkedIn profile URL
analysis (Dict[str, Any]): Analysis results
"""
history_key = f"analysis_history_{self._create_session_key(profile_url)}"
# Get existing history
history = self.get_persistent(history_key) or []
# Add new analysis with timestamp
history.append({
'timestamp': datetime.now().isoformat(),
'analysis': analysis
})
# Keep only last 10 analyses
history = history[-10:]
self.store_persistent(history_key, history)
def get_analysis_history(self, profile_url: str) -> list:
"""
Retrieve analysis history for a profile
Args:
profile_url (str): LinkedIn profile URL
Returns:
list: Analysis history
"""
history_key = f"analysis_history_{self._create_session_key(profile_url)}"
return self.get_persistent(history_key) or []
def clear_session(self, profile_url: str = None) -> None:
"""
Clear session data
Args:
profile_url (str, optional): Specific profile to clear, or all if None
"""
if profile_url:
session_key = self._create_session_key(profile_url)
self.session_data.pop(session_key, None)
else:
self.session_data.clear()
def clear_session_cache(self, profile_url: str = None) -> None:
"""
Clear session cache for a specific profile or all profiles
Args:
profile_url (str, optional): URL to clear cache for. If None, clears all.
"""
if profile_url:
session_key = self._create_session_key(profile_url)
if session_key in self.session_data:
del self.session_data[session_key]
print(f"ποΈ Cleared session cache for: {profile_url}")
else:
self.session_data.clear()
print("ποΈ Cleared all session cache")
def force_refresh_session(self, profile_url: str) -> None:
"""
Force refresh by clearing cache for a specific profile
Args:
profile_url (str): LinkedIn profile URL
"""
self.clear_session_cache(profile_url)
print(f"π Forced refresh for: {profile_url}")
def get_session_summary(self) -> Dict[str, Any]:
"""
Get summary of current session data
Returns:
Dict[str, Any]: Session summary
"""
return {
'active_sessions': len(self.session_data),
'sessions': list(self.session_data.keys()),
'storage_location': self.storage_dir
}
def _create_session_key(self, profile_url: str) -> str:
"""Create a clean session key from profile URL"""
# Extract username or create a hash-like key
import hashlib
return hashlib.md5(profile_url.encode()).hexdigest()[:16]
def _load_persistent_data(self) -> Dict[str, Any]:
"""Load persistent data from disk"""
if os.path.exists(self.persistent_file):
try:
with open(self.persistent_file, 'r', encoding='utf-8') as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
return {}
return {}
def _save_persistent_data(self) -> None:
"""Save persistent data to disk"""
try:
with open(self.persistent_file, 'w', encoding='utf-8') as f:
json.dump(self.persistent_data, f, indent=2, ensure_ascii=False)
except IOError as e:
print(f"Warning: Could not save persistent data: {e}")
def export_data(self, filename: str = None) -> str:
"""
Export all data to a JSON file
Args:
filename (str, optional): Custom filename
Returns:
str: Path to exported file
"""
if not filename:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"linkedin_enhancer_export_{timestamp}.json"
export_path = os.path.join(self.storage_dir, filename)
export_data = {
'session_data': self.session_data,
'persistent_data': self.persistent_data,
'export_timestamp': datetime.now().isoformat()
}
with open(export_path, 'w', encoding='utf-8') as f:
json.dump(export_data, f, indent=2, ensure_ascii=False)
return export_path
|