Download core/multi_process_sync.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 2.49 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/core/multi_process_sync.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/core/multi_process_sync.py
-
curl -L -o multi_process_sync.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/core/multi_process_sync.py
2.49 kB
| from __future__ import annotations | |
| import json | |
| import time | |
| import threading | |
| from pathlib import Path | |
| import os | |
| import logging | |
| from typing import Optional, Dict, Any, Any as AnyType # Any imported twice to be safe if some tools prefer it | |
| logger = logging.getLogger(__name__) | |
| class MultiProcessSync: | |
| """Легковесная синхронизация между процессами Uvicorn""" | |
| def __init__(self, sync_dir=".sync"): | |
| self.sync_dir = Path(sync_dir) | |
| self.sync_dir.mkdir(exist_ok=True) | |
| self.state_file = self.sync_dir / "workers.json" | |
| self._local_version = self._load_version() | |
| def _load_version(self): | |
| """Загружает текущую версию""" | |
| if self.state_file.exists(): | |
| try: | |
| with open(self.state_file, 'r') as f: | |
| data = json.load(f) | |
| return data.get('version', 0) | |
| except Exception as e: | |
| logger.warning(f"Error loading sync file: {e}") | |
| return 0 | |
| return 0 | |
| def notify_state_change(self, change_type: str, data: Optional[Dict[str, Any]] = None): | |
| """ | |
| Уведомляет о изменении состояния. | |
| Args: | |
| change_type: Тип изменения (например, "project_open", "session_mode_change") | |
| data: Дополнительные данные об изменении. | |
| """ | |
| self._local_version += 1 | |
| notification = { | |
| 'version': self._local_version, | |
| 'timestamp': time.time(), | |
| 'type': change_type, | |
| 'data': data or {}, | |
| 'pid': os.getpid() | |
| } | |
| try: | |
| with open(self.state_file, 'w') as f: | |
| json.dump(notification, f, indent=2) | |
| logger.info(f"Notified workers about {change_type} (v{self._local_version})") | |
| except Exception as e: | |
| logger.error(f"Failed to write sync file: {e}") | |
| def check_for_notifications(self) -> bool: | |
| """Проверяет новые уведомления.""" | |
| current_version = self._load_version() | |
| if current_version > self._local_version: | |
| self._local_version = current_version | |
| return True | |
| return False | |
| # Глобальный экземпляр для импорта | |
| multi_process_sync = MultiProcessSync() | |