Spaces:
Configuration error
Configuration error
Update app.py
Browse files
app.py
CHANGED
|
@@ -147,8 +147,186 @@ class DataAnalysisAssistant:
|
|
| 147 |
return f'<div class="analysis-text">{response}</div>'
|
| 148 |
|
| 149 |
class AnalysisHistory:
|
| 150 |
-
"""
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
def process_file(file: gr.File) -> Optional[pd.DataFrame]:
|
| 154 |
"""Process uploaded file into DataFrame."""
|
|
|
|
| 147 |
return f'<div class="analysis-text">{response}</div>'
|
| 148 |
|
| 149 |
class AnalysisHistory:
|
| 150 |
+
"""
|
| 151 |
+
Manages analysis history and persistence.
|
| 152 |
+
|
| 153 |
+
Attributes:
|
| 154 |
+
history_file (Path): Path to the JSON file storing analysis history
|
| 155 |
+
history (List[Dict]): List of historical analysis entries
|
| 156 |
+
|
| 157 |
+
Each history entry is a dictionary containing:
|
| 158 |
+
- timestamp: ISO format timestamp
|
| 159 |
+
- query: The user's analysis query
|
| 160 |
+
- result: The analysis result/response
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
def __init__(self, history_file: str = HISTORY_FILE):
|
| 164 |
+
"""
|
| 165 |
+
Initialize the analysis history manager.
|
| 166 |
+
|
| 167 |
+
Args:
|
| 168 |
+
history_file (str): Path to history JSON file. Defaults to HISTORY_FILE.
|
| 169 |
+
"""
|
| 170 |
+
self.history_file = Path(history_file)
|
| 171 |
+
self.history = self._load_history()
|
| 172 |
+
|
| 173 |
+
def _load_history(self) -> List[Dict]:
|
| 174 |
+
"""
|
| 175 |
+
Load analysis history from file.
|
| 176 |
+
|
| 177 |
+
Returns:
|
| 178 |
+
List[Dict]: List of historical analysis entries
|
| 179 |
+
"""
|
| 180 |
+
if self.history_file.exists():
|
| 181 |
+
try:
|
| 182 |
+
with self.history_file.open('r') as f:
|
| 183 |
+
return json.load(f)
|
| 184 |
+
except json.JSONDecodeError:
|
| 185 |
+
logger.error(f"Invalid JSON in history file: {self.history_file}")
|
| 186 |
+
return []
|
| 187 |
+
except Exception as e:
|
| 188 |
+
logger.error(f"Error loading history file: {str(e)}")
|
| 189 |
+
return []
|
| 190 |
+
return []
|
| 191 |
+
|
| 192 |
+
def add_entry(self, query: str, result: str) -> None:
|
| 193 |
+
"""
|
| 194 |
+
Add a new analysis entry to history.
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
query (str): The analysis query
|
| 198 |
+
result (str): The analysis result/response
|
| 199 |
+
"""
|
| 200 |
+
entry = {
|
| 201 |
+
'timestamp': datetime.now().isoformat(),
|
| 202 |
+
'query': query,
|
| 203 |
+
'result': result
|
| 204 |
+
}
|
| 205 |
+
self.history.append(entry)
|
| 206 |
+
self._save_history()
|
| 207 |
+
|
| 208 |
+
def get_recent_analyses(self, limit: int = 5) -> List[Dict]:
|
| 209 |
+
"""
|
| 210 |
+
Get most recent analysis entries.
|
| 211 |
+
|
| 212 |
+
Args:
|
| 213 |
+
limit (int): Maximum number of entries to return. Defaults to 5.
|
| 214 |
+
|
| 215 |
+
Returns:
|
| 216 |
+
List[Dict]: Recent analysis entries, sorted by timestamp (newest first)
|
| 217 |
+
"""
|
| 218 |
+
return sorted(
|
| 219 |
+
self.history,
|
| 220 |
+
key=lambda x: x['timestamp'],
|
| 221 |
+
reverse=True
|
| 222 |
+
)[:limit]
|
| 223 |
+
|
| 224 |
+
def _save_history(self) -> None:
|
| 225 |
+
"""Save history to file."""
|
| 226 |
+
try:
|
| 227 |
+
with self.history_file.open('w') as f:
|
| 228 |
+
json.dump(self.history, f, indent=2)
|
| 229 |
+
except Exception as e:
|
| 230 |
+
logger.error(f"Failed to save history: {str(e)}")
|
| 231 |
+
|
| 232 |
+
def clear_history(self) -> None:
|
| 233 |
+
"""Clear all analysis history."""
|
| 234 |
+
self.history = []
|
| 235 |
+
self._save_history()
|
| 236 |
+
|
| 237 |
+
def get_history_by_date(self, start_date: datetime, end_date: datetime) -> List[Dict]:
|
| 238 |
+
"""
|
| 239 |
+
Get analysis history within a date range.
|
| 240 |
+
|
| 241 |
+
Args:
|
| 242 |
+
start_date (datetime): Start of date range
|
| 243 |
+
end_date (datetime): End of date range
|
| 244 |
+
|
| 245 |
+
Returns:
|
| 246 |
+
List[Dict]: Analysis entries within the specified date range
|
| 247 |
+
"""
|
| 248 |
+
filtered_history = []
|
| 249 |
+
for entry in self.history:
|
| 250 |
+
try:
|
| 251 |
+
entry_date = datetime.fromisoformat(entry['timestamp'])
|
| 252 |
+
if start_date <= entry_date <= end_date:
|
| 253 |
+
filtered_history.append(entry)
|
| 254 |
+
except Exception as e:
|
| 255 |
+
logger.error(f"Error parsing entry date: {str(e)}")
|
| 256 |
+
continue
|
| 257 |
+
return filtered_history
|
| 258 |
+
|
| 259 |
+
def search_history(self, search_term: str) -> List[Dict]:
|
| 260 |
+
"""
|
| 261 |
+
Search analysis history for a specific term.
|
| 262 |
+
|
| 263 |
+
Args:
|
| 264 |
+
search_term (str): Term to search for in queries and results
|
| 265 |
+
|
| 266 |
+
Returns:
|
| 267 |
+
List[Dict]: Matching analysis entries
|
| 268 |
+
"""
|
| 269 |
+
search_term = search_term.lower()
|
| 270 |
+
return [
|
| 271 |
+
entry for entry in self.history
|
| 272 |
+
if search_term in entry['query'].lower()
|
| 273 |
+
or search_term in entry['result'].lower()
|
| 274 |
+
]
|
| 275 |
+
|
| 276 |
+
def get_statistics(self) -> Dict[str, Any]:
|
| 277 |
+
"""
|
| 278 |
+
Get statistics about the analysis history.
|
| 279 |
+
|
| 280 |
+
Returns:
|
| 281 |
+
Dict[str, Any]: Statistics including total entries, date range, etc.
|
| 282 |
+
"""
|
| 283 |
+
if not self.history:
|
| 284 |
+
return {
|
| 285 |
+
"total_entries": 0,
|
| 286 |
+
"date_range": None,
|
| 287 |
+
"average_entries_per_day": 0
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
dates = [datetime.fromisoformat(entry['timestamp']) for entry in self.history]
|
| 291 |
+
first_date = min(dates)
|
| 292 |
+
last_date = max(dates)
|
| 293 |
+
days_span = (last_date - first_date).days or 1
|
| 294 |
+
|
| 295 |
+
return {
|
| 296 |
+
"total_entries": len(self.history),
|
| 297 |
+
"date_range": {
|
| 298 |
+
"first": first_date.isoformat(),
|
| 299 |
+
"last": last_date.isoformat()
|
| 300 |
+
},
|
| 301 |
+
"average_entries_per_day": len(self.history) / days_span
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
def export_history(self, format: str = 'json') -> str:
|
| 305 |
+
"""
|
| 306 |
+
Export analysis history in specified format.
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
format (str): Export format ('json' or 'csv'). Defaults to 'json'.
|
| 310 |
+
|
| 311 |
+
Returns:
|
| 312 |
+
str: Path to exported file
|
| 313 |
+
|
| 314 |
+
Raises:
|
| 315 |
+
ValueError: If format is not supported
|
| 316 |
+
"""
|
| 317 |
+
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 318 |
+
if format == 'json':
|
| 319 |
+
export_path = f'analysis_history_{timestamp}.json'
|
| 320 |
+
with open(export_path, 'w') as f:
|
| 321 |
+
json.dump(self.history, f, indent=2)
|
| 322 |
+
return export_path
|
| 323 |
+
elif format == 'csv':
|
| 324 |
+
export_path = f'analysis_history_{timestamp}.csv'
|
| 325 |
+
df = pd.DataFrame(self.history)
|
| 326 |
+
df.to_csv(export_path, index=False)
|
| 327 |
+
return export_path
|
| 328 |
+
else:
|
| 329 |
+
raise ValueError(f"Unsupported export format: {format}")
|
| 330 |
|
| 331 |
def process_file(file: gr.File) -> Optional[pd.DataFrame]:
|
| 332 |
"""Process uploaded file into DataFrame."""
|