Spaces:
Running

File size: 7,584 Bytes
8f3b9c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"""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()