Download core/chat_storage.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 4.64 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/core/chat_storage.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/core/chat_storage.py
-
curl -L -o chat_storage.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/core/chat_storage.py
4.64 kB
| import os | |
| import json | |
| import re | |
| import logging | |
| from pathlib import Path | |
| from datetime import datetime | |
| from typing import List, Dict, Optional, Any | |
| logger = logging.getLogger(__name__) | |
| def sanitize_session_id(session_id: str) -> str: | |
| """Защита от path traversal: разрешены только буквы, цифры, _ и -.""" | |
| return re.sub(r'[^a-zA-Z0-9_\-]', '_', session_id) | |
| class ChatStorage: | |
| def __init__(self, base_dir: str = "chats"): | |
| self.base_dir = Path(base_dir) | |
| self._ensure_dir(self.base_dir) | |
| def _ensure_dir(self, path: Path): | |
| if not path.exists(): | |
| path.mkdir(parents=True, exist_ok=True) | |
| def _get_role_dir(self, role: str) -> Path: | |
| role_dir = self.base_dir / role | |
| self._ensure_dir(role_dir) | |
| return role_dir | |
| def _get_session_path(self, session_id: str, role: str) -> Path: | |
| safe_id = sanitize_session_id(session_id) | |
| return self._get_role_dir(role) / f"{safe_id}.json" | |
| def create_session(self, session_id: str, role: str, metadata: Optional[Dict] = None) -> bool: | |
| path = self._get_session_path(session_id, role) | |
| if path.exists(): | |
| return False | |
| session_data = { | |
| "session_id": session_id, | |
| "role": role, | |
| "created_at": datetime.now().isoformat(), | |
| "updated_at": datetime.now().isoformat(), | |
| "metadata": metadata or {}, | |
| "messages": [] | |
| } | |
| self._save_session(path, session_data) | |
| return True | |
| def get_session(self, session_id: str, role: str) -> Optional[Dict]: | |
| path = self._get_session_path(session_id, role) | |
| if not path.exists(): | |
| return None | |
| try: | |
| with open(path, 'r', encoding='utf-8') as f: | |
| return json.load(f) | |
| except Exception as e: | |
| logger.error(f"[ChatStorage] Failed to read {path}: {e}") | |
| return None | |
| def append_message(self, session_id: str, role: str, message: Dict) -> bool: | |
| path = self._get_session_path(session_id, role) | |
| session = self.get_session(session_id, role) | |
| if not session: | |
| return False | |
| message["timestamp"] = datetime.now().isoformat() | |
| session["messages"].append(message) | |
| session["updated_at"] = datetime.now().isoformat() | |
| return self._save_session(path, session) | |
| def list_sessions(self, role: str, limit: int = 50) -> List[Dict]: | |
| role_dir = self._get_role_dir(role) | |
| sessions = [] | |
| try: | |
| # Сортировка по времени модификации (новые сверху) | |
| files = sorted(role_dir.glob("*.json"), key=os.path.getmtime, reverse=True) | |
| for f in files[:limit]: | |
| try: | |
| with open(f, 'r', encoding='utf-8') as sf: | |
| data = json.load(sf) | |
| # Возвращаем только метаданные без сообщений для списка | |
| sessions.append({ | |
| "session_id": data["session_id"], | |
| "created_at": data["created_at"], | |
| "updated_at": data["updated_at"], | |
| "metadata": data.get("metadata", {}), | |
| "message_count": len(data.get("messages", [])) | |
| }) | |
| except Exception as ef: | |
| logger.warning(f"[ChatStorage] Skipping corrupted file {f}: {ef}") | |
| except Exception as e: | |
| logger.error(f"[ChatStorage] Failed to list sessions for {role}: {e}") | |
| return sessions | |
| def _save_session(self, path: Path, data: Dict) -> bool: | |
| tmp_path = path.with_suffix(".tmp") | |
| try: | |
| with open(tmp_path, 'w', encoding='utf-8') as f: | |
| json.dump(data, f, indent=2, ensure_ascii=False) | |
| tmp_path.replace(path) | |
| return True | |
| except Exception as e: | |
| logger.error(f"[ChatStorage] Failed to save {path}: {e}") | |
| if tmp_path.exists(): | |
| try: | |
| os.remove(tmp_path) | |
| except: | |
| pass | |
| return False | |
| _storage_instance = None | |
| def get_chat_storage() -> ChatStorage: | |
| global _storage_instance | |
| if _storage_instance is None: | |
| # Путь относительно корня проекта, где запускается app2.py | |
| _storage_instance = ChatStorage(base_dir="AIColab/chats") | |
| return _storage_instance | |