Spaces:
Running
Running
Download src/core/watcher.py from ArielJoe/Prompt-Builder: direct link, hf CLI and curl.
- Browser
- Download file 7.58 kB
-
https://huggingface.co/spaces/ArielJoe/Prompt-Builder/resolve/main/src/core/watcher.py
- Command line
-
hf download hf://spaces/ArielJoe/Prompt-Builder/src/core/watcher.py
-
curl -L -o watcher.py https://huggingface.co/spaces/ArielJoe/Prompt-Builder/resolve/main/src/core/watcher.py
7.58 kB
| """Development file watchers (hot-reload / process restart) and sub-server lifecycle.""" | |
| from __future__ import annotations | |
| import logging | |
| import subprocess | |
| import sys | |
| import threading | |
| import time | |
| from collections.abc import Callable | |
| from pathlib import Path | |
| from typing import ClassVar | |
| from core.evaluator import DetectorRegistry, PipelineConfig | |
| logger = logging.getLogger(__name__) | |
| class DetectorWatcher: | |
| """Polling watcher that hot-reloads detector packages when source files change.""" | |
| _PACKAGES: ClassVar[tuple[str, ...]] = ( | |
| "pii", | |
| "word_quality", | |
| "risky_content", | |
| "ner", | |
| "profanity", | |
| "filler", | |
| "special_char", | |
| "syntax", | |
| "field_fit", | |
| "thesaurus", | |
| ) | |
| def __init__(self, src_dir: Path, registry: DetectorRegistry, interval: float = 1.5) -> None: | |
| self._src_dir = src_dir | |
| self._registry = registry | |
| self._interval = interval | |
| self._mtimes: dict[Path, float] = {} | |
| self._stop = threading.Event() | |
| def _watched_files(self) -> list[tuple[str, Path]]: | |
| files: list[tuple[str, Path]] = [] | |
| for pkg in self._PACKAGES: | |
| pkg_dir = self._src_dir / pkg | |
| if not pkg_dir.is_dir(): | |
| continue | |
| for path in sorted(pkg_dir.glob("*.py")): | |
| if path.name.endswith("_server.py") or path.name == "__init__.py": | |
| continue | |
| files.append((pkg, path)) | |
| return files | |
| def start(self) -> None: | |
| for _, path in self._watched_files(): | |
| self._mtimes[path] = path.stat().st_mtime | |
| thread = threading.Thread(target=self._loop, daemon=True, name="DetectorWatcher") | |
| thread.start() | |
| logger.info("DetectorWatcher active (polling every %.1fs).", self._interval) | |
| def _loop(self) -> None: | |
| while not self._stop.wait(self._interval): | |
| changed_pkgs: list[str] = [] | |
| for pkg, path in self._watched_files(): | |
| if not path.exists(): | |
| continue | |
| mtime = path.stat().st_mtime | |
| prev = self._mtimes.get(path) | |
| if prev is not None and mtime == prev: | |
| continue | |
| self._mtimes[path] = mtime | |
| if pkg not in changed_pkgs: | |
| changed_pkgs.append(pkg) | |
| for pkg in changed_pkgs: | |
| logger.info("Changes in package '%s' - reloading detector...", pkg) | |
| try: | |
| self._registry.reload(pkg) | |
| logger.info("Reload complete: %s", pkg) | |
| except Exception as exc: | |
| logger.error("Reload failed (%s): %s", pkg, exc) | |
| class PipelineRestartWatcher: | |
| """Polling watcher that restarts the pipeline process when core files change.""" | |
| def __init__( | |
| self, | |
| src_dir: Path, | |
| on_restart: Callable[[str], None], | |
| interval: float = 1.5, | |
| ) -> None: | |
| self._src_dir = src_dir | |
| self._on_restart = on_restart | |
| self._interval = interval | |
| self._mtimes: dict[Path, float] = {} | |
| self._stop = threading.Event() | |
| def _watched_files(self) -> list[Path]: | |
| core_dir = self._src_dir / "core" | |
| if not core_dir.is_dir(): | |
| return [] | |
| return sorted(p for p in core_dir.glob("*.py") if p.name != "__init__.py") | |
| def start(self) -> None: | |
| for path in self._watched_files(): | |
| self._mtimes[path] = path.stat().st_mtime | |
| thread = threading.Thread(target=self._loop, daemon=True, name="PipelineRestartWatcher") | |
| thread.start() | |
| logger.info("PipelineRestartWatcher active (polling every %.1fs).", self._interval) | |
| def _loop(self) -> None: | |
| while not self._stop.wait(self._interval): | |
| for path in self._watched_files(): | |
| if not path.exists(): | |
| continue | |
| mtime = path.stat().st_mtime | |
| if mtime == self._mtimes.get(path): | |
| continue | |
| self._mtimes[path] = mtime | |
| time.sleep(0.25) # Allow editor write to finish flushing. | |
| rel = path.relative_to(self._src_dir) | |
| self._on_restart(f"Core file change detected: {rel}") | |
| class SubserverManager: | |
| """Manages development detector test sub-server processes.""" | |
| def __init__(self, src_dir: Path) -> None: | |
| self._src_dir = src_dir | |
| self._processes: list[subprocess.Popen[bytes]] = [] | |
| def start(self, host: str, cfg: PipelineConfig) -> None: | |
| """Spawn enabled individual detector sub-servers as background processes.""" | |
| specs: list[tuple[str, int, str, list[str]]] = [ | |
| ("pii/pii_server.py", 8002, "PII", []), | |
| ( | |
| "word_quality/word_quality_server.py", | |
| 8003, | |
| "WordQuality", | |
| ["--no-ml"] if cfg.no_resp_ml else [], | |
| ), | |
| ("risky_content/risky_content_server.py", 8004, "RiskyContent", []), | |
| ( | |
| "profanity/profanity_server.py", | |
| 8005, | |
| "Profanity", | |
| ["--no-ml"] if cfg.no_resp_ml else [], | |
| ), | |
| ("filler/filler_server.py", 8006, "Filler", []), | |
| ("special_char/special_char_server.py", 8007, "SpecialChar", []), | |
| ] | |
| if not cfg.no_ner and not cfg.no_ner_ml: | |
| specs.insert(0, ("ner/ner_server.py", 8001, "NER", [])) | |
| else: | |
| logger.info("NER sub-server skipped (fast mode / NER ML disabled).") | |
| if not cfg.no_syntax_ml: | |
| specs.append(("syntax/syntax_server.py", 8008, "Syntax", [])) | |
| else: | |
| logger.info("Syntax sub-server skipped (fast mode / Syntax ML disabled).") | |
| if not cfg.no_fieldfit_ml: | |
| specs.append(("field_fit/field_fit_server.py", 8009, "FieldFit", [])) | |
| else: | |
| logger.info("Field-Fit sub-server skipped (fast mode / Field-Fit ML disabled).") | |
| logger.info("-" * 56) | |
| logger.info("Starting test page sub-servers...") | |
| for script, port, name, extra in specs: | |
| script_path = self._src_dir / script | |
| if not script_path.exists(): | |
| logger.warning("Sub-server %s: script not found (%s)", name, script_path) | |
| continue | |
| try: | |
| proc = subprocess.Popen( | |
| [sys.executable, str(script_path), "--port", str(port), "--host", host, *extra], | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.DEVNULL, | |
| ) | |
| self._processes.append(proc) | |
| logger.info(" %-14s -> http://%s:%-5d (PID %d)", name, host, port, proc.pid) | |
| except OSError as exc: | |
| logger.warning("Sub-server %s failed (port %d in use?): %s", name, port, exc) | |
| except Exception as exc: | |
| logger.warning("Sub-server %s failed: %s", name, exc) | |
| logger.info("-" * 56) | |
| def terminate(self, timeout: float = 2.0) -> None: | |
| """Terminate all spawned sub-server processes cleanly.""" | |
| for proc in list(self._processes): | |
| try: | |
| if proc.poll() is None: | |
| proc.terminate() | |
| try: | |
| proc.wait(timeout=timeout) | |
| except subprocess.TimeoutExpired: | |
| proc.kill() | |
| except Exception: | |
| pass | |
| self._processes.clear() | |