convert voice-analyzer to timer mode

This commit is contained in:
timur 2026-08-05 21:51:18 +05:00
parent f21b130685
commit db79e70876
13 changed files with 129 additions and 91 deletions

View File

@ -61,9 +61,10 @@ voice-pipeline/
│ ├── __init__.py
│ └── __main__.py # voice-pipeline CLI (validate-config, collector…)
├── systemd/
│ ├── voice-collector.service # Uses: voice-pipeline collector
│ ├── voice-collector.timer
│ ├── voice-analyzer.service # Uses: voice-pipeline analyzer
│ ├── voice-collector.service # Uses: voice-pipeline collector
│ ├── voice-collector.timer
│ ├── voice-analyzer.service # Uses: voice-pipeline analyzer
│ ├── voice-analyzer.timer
│ ├── voice-reporter.service # Uses: voice-pipeline reporter
│ └── install.sh
├── config/
@ -136,7 +137,7 @@ Never skip a state. Read the current status before writing.
## Process 1 — Collector
**Entry point:** `collector/main.py`
**Run model:** systemd timer (interval configured in `config.toml → [schedule].collect_interval`)
**Run model:** systemd timer (10-second cadence during 09:00-21:00 local time)
### Asterisk source
@ -167,7 +168,7 @@ Never skip a state. Read the current status before writing.
## Process 2 — Analyzer
**Entry point:** `analyzer/main.py`
**Run model:** systemd service (long-running); polls spool for `status=spooled` records.
**Run model:** systemd timer; each run processes the current spool backlog once.
### Diarization strategy
@ -300,7 +301,7 @@ spool_root = "/var/lib/voice-pipeline/spool"
db_url = "sqlite:////var/lib/voice-pipeline/db.sqlite3"
[schedule]
collect_interval = "5min" # systemd timer OnUnitActiveSec
collect_interval = "10s" # legacy override; deployed timer is hardcoded to 10s
[[sources.asterisk]]
transport = "sftp" # "sftp" | "http"
@ -375,8 +376,8 @@ bash systemd/install.sh
# 3. Creates /var/lib/voice-pipeline/{spool,reports} owned by voice-pipeline
# 4. Reloads systemd and enables all units
systemctl start voice-collector.timer
systemctl start voice-analyzer.service
systemctl start voice-collector.timer
systemctl start voice-analyzer.timer
systemctl start voice-reporter.service
# Logs

View File

@ -168,6 +168,9 @@ Each spooled call gets a `meta.json` file with the structured metadata used by t
## Analyzer behavior
The analyzer is timer-driven and runs in one pass each time the timer fires.
It processes the current backlog, writes artifacts, and exits.
- Asterisk split-channel calls use `rx.wav` and `tx.wav`.
- Mixed audio calls use `audio.mp3` or fallback `mixed.wav` when available.
- Analyzer artifacts are written under `storage.analyzer_artifacts_root/{date}/{uniqueid}`.

View File

@ -44,11 +44,12 @@ level = "INFO"
# Schedule
# ---------------------------------------------------------------------------
[schedule]
# Passed verbatim to OnUnitActiveSec in voice-collector.timer.
# Examples: "5min", "15min", "1h"
collect_interval = "5min"
# Poll interval in seconds for the analyzer, reporter, and importer long-running services.
# Legacy collector cadence override. The default deployment now uses a
# 10-second calendar-based timer during local business hours.
collect_interval = "10s"
# Poll interval in seconds for the reporter and importer long-running services.
# Analyzer now runs from a timer instead of an internal poll loop.
poll_interval_s = 10
@ -107,6 +108,7 @@ webhook_url = "https://your-portal.bitrix24.ru/rest/1/your-token/"
# Number of activities to fetch per API page.
page_size = 50
min_call_duration_s = 0
# When .checkpoint_voximplant is missing, recollect this many days of history.

View File

@ -18,6 +18,7 @@ from core.config import load_config
from core.db import get_session, init_db
from core.logger import configure_logging, get_logger
from core.models import AnalysisArtifact, CallRecord, CallStatus
from core.time_window import is_working_hours
log = get_logger(__name__)
@ -392,13 +393,16 @@ def main() -> None:
cfg = load_config()
configure_logging(level=cfg.logging.level)
init_db()
if not is_working_hours():
log.info("Analyzer outside active window; skipping run")
return
cfg.storage.analyzer_artifacts_root.mkdir(parents=True, exist_ok=True)
(cfg.analyzer.state_dir or (cfg.storage.runtime_state_root / "analyzer")).mkdir(
parents=True, exist_ok=True
)
reset_provider_manager()
log.info("Analyzer service starting", poll_interval_s=cfg.schedule.poll_interval_s)
log.info("Analyzer timer run starting")
from analyzer.emotion import make_emotion_classifier
from analyzer.transcriber import make_transcriber
@ -409,12 +413,9 @@ def main() -> None:
emotion_classifier = make_emotion_classifier()
log.info("Emotion classifier initialized in lazy mode")
from core.daemon import GracefulExit
stop = GracefulExit()
expect_analysis = bool(cfg.analyzer.script_files)
while not stop.requested:
while True:
with get_session() as session:
pending = list(
session.exec(
@ -442,18 +443,12 @@ def main() -> None:
pending.append(record)
if not pending:
log.debug(
"No pending calls; sleeping", seconds=cfg.schedule.poll_interval_s
)
stop.sleep(cfg.schedule.poll_interval_s)
continue
log.info("Analyzer batch complete; no pending calls")
break
log.info("Processing batch", count=len(pending))
for record in pending:
record_uniqueid = getattr(record, "uniqueid", "<detached>")
if stop.requested:
log.info("Shutdown requested; finishing current batch")
break
try:
process_call(record, transcriber, emotion_classifier)
except NoProviderAvailable as exc:
@ -468,7 +463,7 @@ def main() -> None:
error=str(exc),
)
log.info("Analyzer shutting down cleanly")
log.info("Analyzer timer run finished")
if __name__ == "__main__":

View File

@ -20,6 +20,7 @@ from core.config import load_config
from core.db import get_session, init_db
from core.logger import configure_logging, get_logger
from core.models import CallRecord, CallSource, CallStatus
from core.time_window import is_working_hours
log = get_logger(__name__)
@ -253,6 +254,10 @@ def main() -> None:
cfg = load_config()
configure_logging(level=cfg.logging.level)
if not is_working_hours():
log.info("Collector outside active window; skipping run")
return
start = time.monotonic()
log.info("Collector starting")
cfg.storage.spool_root.mkdir(parents=True, exist_ok=True)

19
src/core/time_window.py Normal file
View File

@ -0,0 +1,19 @@
from __future__ import annotations
"""Helpers for local-time execution windows."""
from datetime import datetime
def is_working_hours(
now: datetime | None = None,
*,
start_hour: int = 9,
end_hour: int = 21,
) -> bool:
"""Return True when local time is within the configured hour window."""
current = (now or datetime.now()).astimezone()
return start_hour <= current.hour < end_hour or (
current.hour == end_hour and current.minute == 0
)

View File

@ -80,6 +80,7 @@ for unit in \
voice-collector.service \
voice-collector.timer \
voice-analyzer.service \
voice-analyzer.timer \
voice-reporter.service \
voice-importer.service
do
@ -103,7 +104,7 @@ systemctl daemon-reload
echo "==> Enabling units"
systemctl enable voice-collector.timer
systemctl enable voice-analyzer.service
systemctl enable voice-analyzer.timer
systemctl enable voice-reporter.service
systemctl enable voice-importer.service
@ -118,13 +119,13 @@ echo " 3. Copy scripts/ directory:"
echo " cp -r scripts/ ${CONFIG_DIR}/scripts/"
echo " 4. Start services:"
echo " systemctl start voice-collector.timer"
echo " systemctl start voice-analyzer.service"
echo " systemctl start voice-analyzer.timer"
echo " systemctl start voice-reporter.service"
echo " systemctl start voice-importer.service"
echo ""
echo " Check status:"
echo " systemctl status voice-collector.timer"
echo " systemctl status voice-analyzer.service"
echo " systemctl status voice-analyzer.timer"
echo " systemctl status voice-reporter.service"
echo " systemctl status voice-importer.service"
echo ""

View File

@ -1,36 +1,26 @@
[Unit]
Description=Voice Pipeline — Analyzer (long-running)
Documentation=file:/etc/voice-pipeline/config.toml
After=network-online.target
Wants=network-online.target
# Restart rate-limit: give up after 5 restarts in 5 minutes
StartLimitIntervalSec=300
StartLimitBurst=5
# Collector is scheduled independently; analyzer can start on its own and poll the DB.
[Service]
Type=simple
User=voice-pipeline
Group=voice-pipeline
[Unit]
Description=Voice Pipeline — Analyzer (timer-driven)
Documentation=file:/etc/voice-pipeline/config.toml
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
User=voice-pipeline
Group=voice-pipeline
# ── Environment ────────────────────────────────────────────────────────────
Environment=VOICE_PIPELINE_CONFIG=/etc/voice-pipeline/config.toml
# secrets.env is loaded by the application from /etc/voice-pipeline/secrets.env
# ── Process ────────────────────────────────────────────────────────────────
WorkingDirectory=/opt/voice-pipeline
ExecStart=/opt/voice-pipeline/venv/bin/voice-pipeline analyzer
# ── Restart policy ─────────────────────────────────────────────────────────
# Analyzer exits cleanly when all providers are exhausted; restart so it can recover
# after credentials, network, quota, or provider availability improve.
Restart=always
RestartSec=15s
# ── Logging ────────────────────────────────────────────────────────────────
StandardOutput=journal
StandardError=journal
SyslogIdentifier=voice-analyzer
# ── Process ────────────────────────────────────────────────────────────────
WorkingDirectory=/opt/voice-pipeline
ExecStart=/opt/voice-pipeline/venv/bin/voice-pipeline analyzer
# ── Logging ────────────────────────────────────────────────────────────────
StandardOutput=journal
StandardError=journal
SyslogIdentifier=voice-analyzer
# ── Timeouts ───────────────────────────────────────────────────────────────
# Model initialization can be slow on first boot, especially with local ASR,
@ -61,9 +51,6 @@ ProtectKernelModules=true
ProtectControlGroups=true
SystemCallFilter=@system-service @network-io @file-system
SystemCallErrorNumber=EPERM
RestrictRealtime=true
RestrictSUIDSGID=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
[Install]
WantedBy=multi-user.target
RestrictRealtime=true
RestrictSUIDSGID=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX

View File

@ -0,0 +1,18 @@
[Unit]
Description=Voice Pipeline — Analyzer timer
Documentation=file:/etc/voice-pipeline/config.toml
Requires=voice-analyzer.service
[Timer]
# Fire every 10 seconds during local business hours, with a final 21:00 tick.
OnCalendar=*-*-* 09..20:*:00/10
OnCalendar=*-*-* 21:00:00
# Allow up to 1 second of jitter on a lightly loaded host.
AccuracySec=1s
# If the system was offline, run once on boot when the timer is active again.
Persistent=true
[Install]
WantedBy=timers.target

View File

@ -40,9 +40,6 @@ ProtectKernelModules=true
ProtectControlGroups=true
SystemCallFilter=@system-service @network-io @file-system
SystemCallErrorNumber=EPERM
RestrictRealtime=true
RestrictSUIDSGID=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
[Install]
WantedBy=multi-user.target
RestrictRealtime=true
RestrictSUIDSGID=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX

View File

@ -1,22 +1,19 @@
[Unit]
Description=Voice Pipeline — Collector timer
Documentation=file:/etc/voice-pipeline/config.toml
Requires=voice-collector.service
[Timer]
# Fire 60 s after boot (gives network and other services time to settle)
OnBootSec=60s
# Then repeat every N minutes after the last run completed.
# Must match [schedule].collect_interval in config.toml.
OnUnitActiveSec=5min
# Allow up to 30 s of jitter to avoid thundering-herd on a shared host
AccuracySec=30s
# If the system was offline and missed one or more runs, execute once
# immediately on next boot to catch up rather than waiting the full interval
Persistent=true
[Unit]
Description=Voice Pipeline — Collector timer
Documentation=file:/etc/voice-pipeline/config.toml
Requires=voice-collector.service
[Timer]
# Fire every 10 seconds during local business hours, with a final 21:00 tick.
OnCalendar=*-*-* 09..20:*:00/10
OnCalendar=*-*-* 21:00:00
# Allow up to 1 second of jitter on a lightly loaded host.
AccuracySec=1s
# If the system was offline and missed one or more runs, execute once
# immediately on next boot to catch up rather than waiting the full interval
Persistent=true
[Install]
WantedBy=timers.target

View File

@ -883,7 +883,7 @@ class TestVoximplantCollectorService:
cfg = Bitrix24SourceConfig(
webhook_url="https://example/rest/1/token/",
page_size=2,
min_call_duration_s=10,
min_call_duration_s=15,
)
service = VoximplantCollectorService(cfg, [])
@ -901,7 +901,7 @@ class TestVoximplantCollectorService:
"ID": "1",
"CALL_ID": "call-1",
"EXTERNAL_CALL_ID": "ext-1",
"CALL_DURATION": "5",
"CALL_DURATION": "15",
"CALL_START_DATE": "2026-06-27T09:00:00+00:00",
"PHONE_NUMBER": "+7999",
"CRM_ENTITY_TYPE": "LEAD",

13
tests/test_time_window.py Normal file
View File

@ -0,0 +1,13 @@
from __future__ import annotations
from datetime import datetime
def test_is_working_hours_includes_start_and_21_00_boundary():
from core.time_window import is_working_hours
assert is_working_hours(datetime(2026, 8, 5, 9, 0))
assert is_working_hours(datetime(2026, 8, 5, 20, 59))
assert is_working_hours(datetime(2026, 8, 5, 21, 0))
assert not is_working_hours(datetime(2026, 8, 5, 8, 59))
assert not is_working_hours(datetime(2026, 8, 5, 21, 1))