parthnuwal7 commited on
Commit
baecac6
·
1 Parent(s): 6a45d88

FIX: Complete DataManager session management

Browse files

Added missing load_session() method
Added save_session() method for session persistence
Enhanced get_history_list() with error handling
Backward compatibility for different data formats
Robust directory handling (creates if missing)

Status: Session management fully functional with JSON storage

Files changed (2) hide show
  1. frontend_light.py +1 -1
  2. src/utils/data_management.py +96 -17
frontend_light.py CHANGED
@@ -20,7 +20,7 @@ st.set_page_config(
20
  )
21
 
22
  # Configuration
23
- HF_SPACES_API_URL = "https://your-username-absa-backend.hf.space" # Update with your HF Space URL
24
 
25
  def call_ml_backend(data: Dict) -> Dict:
26
  """Call the ML backend API on HF Spaces."""
 
20
  )
21
 
22
  # Configuration
23
+ HF_SPACES_API_URL = "https://huggingface.co/spaces/parthnuwal7/ABSA" # Update with your HF Space URL
24
 
25
  def call_ml_backend(data: Dict) -> Dict:
26
  """Call the ML backend API on HF Spaces."""
src/utils/data_management.py CHANGED
@@ -101,26 +101,105 @@ class DataManager:
101
 
102
  def get_history_list(self) -> List[Dict[str, Any]]:
103
  """Get list of all saved dashboard histories."""
104
- history_files = [f for f in os.listdir(self.history_path) if f.endswith('.json')]
105
- history_list = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
- for filename in history_files:
108
- filepath = os.path.join(self.history_path, filename)
 
 
 
 
 
 
 
 
 
 
 
 
109
  try:
110
- with open(filepath, 'r') as f:
111
- history_entry = json.load(f)
112
- history_list.append({
113
- 'id': history_entry['id'],
114
- 'timestamp': history_entry['timestamp'],
115
- 'total_reviews': history_entry['metadata']['total_reviews'],
116
- 'data_file': history_entry['metadata']['data_file']
117
- })
118
- except Exception as e:
119
- st.error(f"Error loading history file {filename}: {str(e)}")
120
 
121
- # Sort by timestamp descending
122
- history_list.sort(key=lambda x: x['timestamp'], reverse=True)
123
- return history_list
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
  def load_dashboard_history(self, history_id: str) -> Optional[Dict[str, Any]]:
126
  """Load specific dashboard history."""
 
101
 
102
  def get_history_list(self) -> List[Dict[str, Any]]:
103
  """Get list of all saved dashboard histories."""
104
+ try:
105
+ # Ensure directory exists
106
+ os.makedirs(self.history_path, exist_ok=True)
107
+
108
+ history_files = [f for f in os.listdir(self.history_path) if f.endswith('.json')]
109
+ history_list = []
110
+
111
+ for filename in history_files:
112
+ filepath = os.path.join(self.history_path, filename)
113
+ try:
114
+ with open(filepath, 'r') as f:
115
+ history_entry = json.load(f)
116
+
117
+ # Handle different data formats for backward compatibility
118
+ entry_data = {
119
+ 'id': history_entry.get('id', filename.replace('.json', '')),
120
+ 'timestamp': history_entry.get('timestamp', datetime.now().isoformat()),
121
+ 'total_reviews': 0,
122
+ 'data_file': filename
123
+ }
124
+
125
+ # Try to get metadata
126
+ if 'metadata' in history_entry:
127
+ entry_data['total_reviews'] = history_entry['metadata'].get('total_reviews', 0)
128
+ entry_data['data_file'] = history_entry['metadata'].get('data_file', filename)
129
+ elif 'summary' in history_entry:
130
+ entry_data['total_reviews'] = history_entry['summary'].get('total_reviews', 0)
131
+
132
+ history_list.append(entry_data)
133
+
134
+ except Exception as e:
135
+ # Log error but don't break the whole function
136
+ print(f"Warning: Error loading history file {filename}: {str(e)}")
137
+ continue
138
+
139
+ # Sort by timestamp descending
140
+ history_list.sort(key=lambda x: x['timestamp'], reverse=True)
141
+ return history_list
142
+
143
+ except Exception as e:
144
+ print(f"Error accessing history directory: {str(e)}")
145
+ return [] # Return empty list instead of failing
146
+
147
+ def get_all_sessions(self) -> List[Dict[str, Any]]:
148
+ """Get all sessions - alias for get_history_list for backward compatibility."""
149
+ return self.get_history_list()
150
+
151
+ def load_session(self, session_id: str) -> Optional[Dict[str, Any]]:
152
+ """
153
+ Load a specific session by ID.
154
 
155
+ Args:
156
+ session_id: Session identifier
157
+
158
+ Returns:
159
+ Session data if found, None otherwise
160
+ """
161
+ # Try loading from history
162
+ session_data = self.load_dashboard_history(session_id)
163
+ if session_data:
164
+ return session_data
165
+
166
+ # Try loading from processed data
167
+ processed_file = os.path.join(self.processed_path, f"processed_{session_id}.json")
168
+ if os.path.exists(processed_file):
169
  try:
170
+ with open(processed_file, 'r') as f:
171
+ return json.load(f)
172
+ except (json.JSONDecodeError, IOError):
173
+ return None
 
 
 
 
 
 
174
 
175
+ return None
176
+
177
+ def save_session(self, session_id: str, session_data: Dict[str, Any]) -> bool:
178
+ """
179
+ Save session data.
180
+
181
+ Args:
182
+ session_id: Session identifier
183
+ session_data: Data to save
184
+
185
+ Returns:
186
+ True if successful, False otherwise
187
+ """
188
+ try:
189
+ # Save to history
190
+ history_file = os.path.join(self.history_path, f"history_{session_id}.json")
191
+
192
+ # Add metadata
193
+ session_data['session_id'] = session_id
194
+ session_data['timestamp'] = datetime.now().isoformat()
195
+
196
+ with open(history_file, 'w') as f:
197
+ json.dump(session_data, f, cls=CustomJSONEncoder, indent=2)
198
+
199
+ return True
200
+ except Exception as e:
201
+ print(f"Error saving session {session_id}: {str(e)}")
202
+ return False
203
 
204
  def load_dashboard_history(self, history_id: str) -> Optional[Dict[str, Any]]:
205
  """Load specific dashboard history."""