fix begin analize with activity

This commit is contained in:
timur 2026-06-26 21:47:33 +05:00
parent 9c4cc76edd
commit 307e2bf6d4
48 changed files with 8861 additions and 7421 deletions

64
.gitignore vendored
View File

@ -1,32 +1,32 @@
tmp/
.pytest_cache/
__pycache__/
*.pyc
*.pyo
*.pyd
*.log
*.sqlite3
*.db
*.env
.env.*
venv/
.venv/
.idea/
.DS_Store
*.swp
*.swo
*.bak
*.tmp
*.log
*.csv
*.xlsx
*.pdf
*.zip
*.tar.gz
*.egg-info/
dist/
build/
*.egg
*.egg-info
tmp/
.pytest_cache/
__pycache__/
*.pyc
*.pyo
*.pyd
*.log
*.sqlite3
*.db
*.env
.env.*
venv/
.venv/
.idea/
.DS_Store
*.swp
*.swo
*.bak
*.tmp
*.log
*.csv
*.xlsx
*.pdf
*.zip
*.tar.gz
*.egg-info/
dist/
build/
*.egg
*.egg-info

726
CLAUDE.md
View File

@ -1,363 +1,363 @@
# CLAUDE.md — voice-pipeline
This file is the canonical reference for Claude (and any AI assistant) working on this codebase.
Read it fully before making any changes.
---
## Project overview
A three-process Python service that ingests voice call recordings, analyses them with LLMs,
and pushes results back to Bitrix24 as activities and reports.
```
collector → spool (local FS) → analyzer → artifacts → reporter → Bitrix24 + reports
```
All three processes run as **systemd units** under the unprivileged system user `voice-pipeline`.
Configuration is loaded from a single TOML file (path set via `VOICE_PIPELINE_CONFIG` env var,
default `/etc/voice-pipeline/config.toml`).
---
## Repository layout
```
voice-pipeline/
├── src/ # All application code lives here (src layout)
│ ├── collector/ # Process 1 — fetch & spool
│ │ ├── __init__.py
│ │ ├── asterisk.py # SFTP + HTTP transport; 3-file set download
│ │ ├── bitrix_source.py # Bitrix24 call activity fetch (MP3, mixed only)
│ │ ├── spooler.py # Atomic spool writer
│ │ └── main.py # Entry point (voice-pipeline collector)
│ ├── analyzer/ # Process 2 — transcribe, align, analyse
│ │ ├── __init__.py
│ │ ├── transcriber.py # Pluggable Whisper backend (cloud / local)
│ │ ├── diarizer.py # rx/tx alignment (Asterisk) + pyannote fallback
│ │ ├── emotion.py # Per-segment emotion scoring
│ │ ├── script_check.py # LLM-based script compliance + ranking
│ │ └── main.py
│ ├── reporter/ # Process 3 — push results
│ │ ├── __init__.py
│ │ ├── bitrix_push.py # Create activity, attach transcript
│ │ ├── report_detail.py # Per-call HTML report (Jinja2)
│ │ ├── report_summary.py # Batch summary report
│ │ ├── main.py
│ │ └── templates/ # Jinja2 HTML templates
│ │ ├── base.html.j2
│ │ ├── report_detail.html.j2
│ │ └── report_summary.html.j2
│ ├── core/ # Shared by all three processes
│ │ ├── __init__.py
│ │ ├── config.py # Pydantic Settings — loads config.toml
│ │ ├── models.py # SQLModel ORM — CallRecord, AnalysisArtifact
│ │ ├── db.py # Engine + session factory
│ │ ├── bitrix_client.py # Thin httpx wrapper for Bitrix24 REST API
│ │ └── logger.py # loguru — structured JSON, syslog-compatible
│ └── voice_pipeline/ # CLI entry point package
│ ├── __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-reporter.service # Uses: voice-pipeline reporter
│ └── install.sh
├── config/
│ └── config.example.toml # Fully commented reference config
├── scripts/
│ ├── inbound_support.toml # Script compliance definition (inbound)
│ ├── outbound_sales.toml # Script compliance definition (outbound)
│ └── README.md
├── tests/
│ ├── test_collector.py
│ ├── test_diarizer.py
│ ├── test_script_check.py
│ ├── test_reporter.py
│ └── test_integration.py
├── pyproject.toml # src layout: packages.find.where = ["src"]
└── CLAUDE.md # ← you are here
```
---
## Spool directory contract
The spool directory is the **only coupling point** between the three processes.
Do not break this contract without updating all three processes.
### Layout
```
{spool_root}/
{YYYY-MM-DD}/
{UNIQUEID}/
mixed.wav # always present for Asterisk source
rx.wav # agent-side audio — Asterisk source only
tx.wav # customer-side audio — Asterisk source only
audio.mp3 # Bitrix24 source only (mixed, no rx/tx)
meta.json # written last, atomically — signals readiness
```
### `meta.json` schema
```jsonc
{
"uniqueid": "1701234567.42", // Asterisk UNIQUEID or Bitrix24 call ID
"source": "asterisk", // "asterisk" | "bitrix24"
"has_rx_tx": true, // true = deterministic diarization available
"direction": "inbound", // "inbound" | "outbound"
"duration_s": 142,
"caller_phone": "+79161234567",
"user_id": "12", // Bitrix24 portal user ID
"entity_type": "LEAD", // "LEAD" | "CONTACT" | "COMPANY" | null
"entity_id": "456",
"fetched_at": "2024-01-15T09:23:11Z",
"status": "spooled" // see status lifecycle below
}
```
### Status lifecycle
```
spooled → processing → analyzed → reporting → reported
↘ failed → dead_letter
```
Only the owning process writes its own status transition.
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`)
### Asterisk source
- Connects via SFTP (`paramiko`) or HTTP (`httpx`) — configured per source in `[[sources.asterisk]]`
- Lists remote files matching glob `*{UNIQUEID}*` and groups into sets of 3:
`{UNIQUEID}.wav` / `{UNIQUEID}-rx.wav` / `{UNIQUEID}-tx.wav`
(exact filename pattern is config-driven — see `sources.asterisk.filename_pattern`)
- **Never spool a partial set.** All 3 files must be present and size-stable
(re-checked after `sources.asterisk.stability_wait_s`, default 5 s) before download begins.
- Tracks last checkpoint as a UTC timestamp in `{spool_root}/.collector_checkpoint`
- Writes files to a temp directory, then renames the whole `{UNIQUEID}/` directory atomically,
then writes `meta.json` last.
### Bitrix24 source
- Uses `crm.activity.list` filtered by `TYPE_ID=2` (calls) and date range since checkpoint
- Downloads MP3 via `disk.file.get` → `DOWNLOAD_URL`
- Resolves entity: `crm.contact.getByPhone` / `crm.lead.getByPhone` using caller phone
- Spools as `audio.mp3` with `has_rx_tx: false`
### Error handling
- Per-call errors are logged and skipped; the checkpoint only advances past fully-spooled calls.
- SFTP/HTTP failures retry up to `sources.retry_attempts` times with exponential backoff.
---
## Process 2 — Analyzer
**Entry point:** `analyzer/main.py`
**Run model:** systemd service (long-running); polls spool for `status=spooled` records.
### Diarization strategy
This is the core correctness requirement — **do not change without updating both branches**:
| `has_rx_tx` | Strategy |
|---|---|
| `true` (Asterisk) | Transcribe `rx.wav` and `tx.wav` separately via Whisper. `rx` = **agent**, `tx` = **customer**. Merge segments by `start` timestamp. No diarization model needed. |
| `false` (Bitrix24) | Transcribe `audio.mp3` via Whisper. Run `pyannote/speaker-diarization-3.1`. Map first speaker to **agent** (heuristic — override via config `analyzer.first_speaker_is_agent`). |
### Transcript artifact format
`{UNIQUEID}/transcript.json`:
```jsonc
[
{
"speaker": "agent", // "agent" | "customer"
"start": 0.54, // seconds from call start
"end": 3.21,
"text": "Добрый день, компания Ромашка.",
"emotion": "neutral", // see emotion labels below
"emotion_score": 0.87
}
]
```
Emotion labels: `neutral`, `positive`, `negative`, `angry`, `fearful`, `surprised`, `sad`
### Script compliance artifact format
`{UNIQUEID}/analysis.json`:
```jsonc
{
"script_id": "inbound_v3",
"score": 74, // 0–100
"summary": "...",
"checklist": [
{ "item": "Greeted with company name", "passed": true, "evidence": "Добрый день, компания..." },
{ "item": "Offered callback", "passed": false, "evidence": null }
]
}
```
### LLM calls
- All LLM calls go through `core/llm.py` — a thin wrapper that selects cloud (Claude/GPT-4o)
or local (Ollama) based on `[llm]` config section.
- Always request **JSON output**. Validate against the schema before writing the artifact.
If the response is not valid JSON after 2 retries, mark the call `status=failed`.
- Never pass audio bytes directly to the LLM. Transcription happens first; LLM sees text only.
---
## Process 3 — Reporter
**Entry point:** `reporter/main.py`
**Run model:** systemd service (long-running); polls for `status=analyzed`.
### Bitrix24 activity creation
- `crm.activity.add` with:
- `TYPE_ID = 2` (call)
- `SUBJECT = f"Call analysis — {entity_type} {entity_id} — {date}"`
- `DESCRIPTION` = plain-text transcript (truncated to 10 000 chars if needed)
- Attach `transcript.json` via Bitrix24 disk API and bind to the activity.
- On success: update `meta.json` `status → reporting`, then `→ reported`.
### Reports
- **Per-call:** `{UNIQUEID}/report_detail.html` — Jinja2 template; includes call metadata,
diarized transcript with emotion badges, script checklist table, score gauge.
- **Batch summary:** `reports/summary_{YYYY-MM-DD}.html` — aggregates calls in a configurable
window; metrics: call count, avg score, emotion distribution, compliance rate per agent.
- Report templates live in `reporter/templates/`. Do not hard-code HTML in Python.
---
## Configuration (`config.toml`)
All settings have documented defaults in `config/config.example.toml`.
Required fields that have no default will raise `ValidationError` on startup — check the log.
Key sections:
```toml
[storage]
spool_root = "/var/lib/voice-pipeline/spool"
db_url = "sqlite:////var/lib/voice-pipeline/db.sqlite3"
[schedule]
collect_interval = "5min" # systemd timer OnUnitActiveSec
[[sources.asterisk]]
transport = "sftp" # "sftp" | "http"
host = "pbx.example.com"
# ... credentials, path, filename_pattern
[sources.bitrix24]
webhook_url = "https://portal.bitrix24.ru/rest/1/xxxx/"
[llm]
backend = "cloud" # "cloud" | "local"
provider = "anthropic" # "anthropic" | "openai" (cloud only)
model = "claude-sonnet-4-6"
# local: ollama_url, model_name
[analyzer]
whisper_backend = "openai" # "openai" | "faster-whisper"
first_speaker_is_agent = true
emotion_backend = "transformers" # "transformers" | "llm"
```
---
## Development setup
```bash
# Create and activate venv
python3 -m venv .venv && source .venv/bin/activate
# Install with dev extras (src/ layout — no PYTHONPATH needed)
pip install -e ".[dev]"
# Add ML backends as needed:
# pip install -e ".[dev,cloud]" # OpenAI Whisper + Anthropic
# pip install -e ".[dev,local-asr]" # faster-whisper (local CPU/GPU)
# pip install -e ".[dev,diarize]" # pyannote (Bitrix24 diarization)
# pip install -e ".[dev,emotion]" # transformers emotion model
# pip install -e ".[local,dev]" # everything
# Copy and edit config
cp config/config.example.toml config/config.toml
export VOICE_PIPELINE_CONFIG=$(pwd)/config/config.toml
# Run a process manually via the installed CLI entry point
voice-pipeline collector
voice-pipeline analyzer
voice-pipeline reporter
# Validate config and connectivity
voice-pipeline validate-config
# Run tests (pythonpath = ["src"] set in pyproject.toml)
pytest tests/ -v
```
---
## Systemd deployment
```bash
# Run as root or with sudo
bash systemd/install.sh
# The install script:
# 1. Creates system user 'voice-pipeline' if absent
# 2. Copies unit files to /etc/systemd/system/
# 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-reporter.service
# Logs
journalctl -u voice-collector -f
journalctl -u voice-analyzer -f
journalctl -u voice-reporter -f
```
---
## Coding conventions
- Python 3.11+. Use `match`/`case` where it aids clarity.
- Type-annotate all public functions. Use `from __future__ import annotations`.
- Pydantic models for all data crossing process or I/O boundaries.
- `loguru` for all logging — never `print()`. Include `uniqueid=` in every log record touching a call.
- All external I/O (SFTP, HTTP, Bitrix24 API, LLM API) must be wrapped in retry logic
from `core/retry.py` (exponential backoff, configurable attempts).
- Tests use `pytest`. Fixtures for audio files live in `tests/fixtures/`.
Do not make real network calls in tests — mock at the transport layer.
- Format with `ruff format`, lint with `ruff check`. Config in `pyproject.toml`.
---
## Key constraints — do not violate
1. **`meta.json` is written last, atomically** (temp file → `os.rename`). This is the readiness signal.
2. **Never spool a partial 3-file set** from Asterisk. All 3 WAVs must be present and size-stable first.
3. **`rx.wav` = agent, `tx.wav` = customer** — this mapping is fixed and must never be reversed.
4. **LLM sees text only** — never pass audio to the LLM. Transcription always happens first.
5. **Status transitions are append-only** — never go backwards in the lifecycle.
6. **All processes run as `voice-pipeline` user** — no root privileges at runtime.
# CLAUDE.md — voice-pipeline
This file is the canonical reference for Claude (and any AI assistant) working on this codebase.
Read it fully before making any changes.
---
## Project overview
A three-process Python service that ingests voice call recordings, analyses them with LLMs,
and pushes results back to Bitrix24 as activities and reports.
```
collector → spool (local FS) → analyzer → artifacts → reporter → Bitrix24 + reports
```
All three processes run as **systemd units** under the unprivileged system user `voice-pipeline`.
Configuration is loaded from a single TOML file (path set via `VOICE_PIPELINE_CONFIG` env var,
default `/etc/voice-pipeline/config.toml`).
---
## Repository layout
```
voice-pipeline/
├── src/ # All application code lives here (src layout)
│ ├── collector/ # Process 1 — fetch & spool
│ │ ├── __init__.py
│ │ ├── asterisk.py # SFTP + HTTP transport; 3-file set download
│ │ ├── bitrix_source.py # Bitrix24 call activity fetch (MP3, mixed only)
│ │ ├── spooler.py # Atomic spool writer
│ │ └── main.py # Entry point (voice-pipeline collector)
│ ├── analyzer/ # Process 2 — transcribe, align, analyse
│ │ ├── __init__.py
│ │ ├── transcriber.py # Pluggable Whisper backend (cloud / local)
│ │ ├── diarizer.py # rx/tx alignment (Asterisk) + pyannote fallback
│ │ ├── emotion.py # Per-segment emotion scoring
│ │ ├── script_check.py # LLM-based script compliance + ranking
│ │ └── main.py
│ ├── reporter/ # Process 3 — push results
│ │ ├── __init__.py
│ │ ├── bitrix_push.py # Create activity, attach transcript
│ │ ├── report_detail.py # Per-call HTML report (Jinja2)
│ │ ├── report_summary.py # Batch summary report
│ │ ├── main.py
│ │ └── templates/ # Jinja2 HTML templates
│ │ ├── base.html.j2
│ │ ├── report_detail.html.j2
│ │ └── report_summary.html.j2
│ ├── core/ # Shared by all three processes
│ │ ├── __init__.py
│ │ ├── config.py # Pydantic Settings — loads config.toml
│ │ ├── models.py # SQLModel ORM — CallRecord, AnalysisArtifact
│ │ ├── db.py # Engine + session factory
│ │ ├── bitrix_client.py # Thin httpx wrapper for Bitrix24 REST API
│ │ └── logger.py # loguru — structured JSON, syslog-compatible
│ └── voice_pipeline/ # CLI entry point package
│ ├── __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-reporter.service # Uses: voice-pipeline reporter
│ └── install.sh
├── config/
│ └── config.example.toml # Fully commented reference config
├── scripts/
│ ├── inbound_support.toml # Script compliance definition (inbound)
│ ├── outbound_sales.toml # Script compliance definition (outbound)
│ └── README.md
├── tests/
│ ├── test_collector.py
│ ├── test_diarizer.py
│ ├── test_script_check.py
│ ├── test_reporter.py
│ └── test_integration.py
├── pyproject.toml # src layout: packages.find.where = ["src"]
└── CLAUDE.md # ← you are here
```
---
## Spool directory contract
The spool directory is the **only coupling point** between the three processes.
Do not break this contract without updating all three processes.
### Layout
```
{spool_root}/
{YYYY-MM-DD}/
{UNIQUEID}/
mixed.wav # always present for Asterisk source
rx.wav # agent-side audio — Asterisk source only
tx.wav # customer-side audio — Asterisk source only
audio.mp3 # Bitrix24 source only (mixed, no rx/tx)
meta.json # written last, atomically — signals readiness
```
### `meta.json` schema
```jsonc
{
"uniqueid": "1701234567.42", // Asterisk UNIQUEID or Bitrix24 call ID
"source": "asterisk", // "asterisk" | "bitrix24"
"has_rx_tx": true, // true = deterministic diarization available
"direction": "inbound", // "inbound" | "outbound"
"duration_s": 142,
"caller_phone": "+79161234567",
"user_id": "12", // Bitrix24 portal user ID
"entity_type": "LEAD", // "LEAD" | "CONTACT" | "COMPANY" | null
"entity_id": "456",
"fetched_at": "2024-01-15T09:23:11Z",
"status": "spooled" // see status lifecycle below
}
```
### Status lifecycle
```
spooled → processing → analyzed → reporting → reported
↘ failed → dead_letter
```
Only the owning process writes its own status transition.
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`)
### Asterisk source
- Connects via SFTP (`paramiko`) or HTTP (`httpx`) — configured per source in `[[sources.asterisk]]`
- Lists remote files matching glob `*{UNIQUEID}*` and groups into sets of 3:
`{UNIQUEID}.wav` / `{UNIQUEID}-rx.wav` / `{UNIQUEID}-tx.wav`
(exact filename pattern is config-driven — see `sources.asterisk.filename_pattern`)
- **Never spool a partial set.** All 3 files must be present and size-stable
(re-checked after `sources.asterisk.stability_wait_s`, default 5 s) before download begins.
- Tracks last checkpoint as a UTC timestamp in `{spool_root}/.collector_checkpoint`
- Writes files to a temp directory, then renames the whole `{UNIQUEID}/` directory atomically,
then writes `meta.json` last.
### Bitrix24 source
- Uses `crm.activity.list` filtered by `TYPE_ID=2` (calls) and date range since checkpoint
- Downloads MP3 via `disk.file.get` → `DOWNLOAD_URL`
- Resolves entity: `crm.contact.getByPhone` / `crm.lead.getByPhone` using caller phone
- Spools as `audio.mp3` with `has_rx_tx: false`
### Error handling
- Per-call errors are logged and skipped; the checkpoint only advances past fully-spooled calls.
- SFTP/HTTP failures retry up to `sources.retry_attempts` times with exponential backoff.
---
## Process 2 — Analyzer
**Entry point:** `analyzer/main.py`
**Run model:** systemd service (long-running); polls spool for `status=spooled` records.
### Diarization strategy
This is the core correctness requirement — **do not change without updating both branches**:
| `has_rx_tx` | Strategy |
|---|---|
| `true` (Asterisk) | Transcribe `rx.wav` and `tx.wav` separately via Whisper. `rx` = **agent**, `tx` = **customer**. Merge segments by `start` timestamp. No diarization model needed. |
| `false` (Bitrix24) | Transcribe `audio.mp3` via Whisper. Run `pyannote/speaker-diarization-3.1`. Map first speaker to **agent** (heuristic — override via config `analyzer.first_speaker_is_agent`). |
### Transcript artifact format
`{UNIQUEID}/transcript.json`:
```jsonc
[
{
"speaker": "agent", // "agent" | "customer"
"start": 0.54, // seconds from call start
"end": 3.21,
"text": "Добрый день, компания Ромашка.",
"emotion": "neutral", // see emotion labels below
"emotion_score": 0.87
}
]
```
Emotion labels: `neutral`, `positive`, `negative`, `angry`, `fearful`, `surprised`, `sad`
### Script compliance artifact format
`{UNIQUEID}/analysis.json`:
```jsonc
{
"script_id": "inbound_v3",
"score": 74, // 0–100
"summary": "...",
"checklist": [
{ "item": "Greeted with company name", "passed": true, "evidence": "Добрый день, компания..." },
{ "item": "Offered callback", "passed": false, "evidence": null }
]
}
```
### LLM calls
- All LLM calls go through `core/llm.py` — a thin wrapper that selects cloud (Claude/GPT-4o)
or local (Ollama) based on `[llm]` config section.
- Always request **JSON output**. Validate against the schema before writing the artifact.
If the response is not valid JSON after 2 retries, mark the call `status=failed`.
- Never pass audio bytes directly to the LLM. Transcription happens first; LLM sees text only.
---
## Process 3 — Reporter
**Entry point:** `reporter/main.py`
**Run model:** systemd service (long-running); polls for `status=analyzed`.
### Bitrix24 activity creation
- `crm.activity.add` with:
- `TYPE_ID = 2` (call)
- `SUBJECT = f"Call analysis — {entity_type} {entity_id} — {date}"`
- `DESCRIPTION` = plain-text transcript (truncated to 10 000 chars if needed)
- Attach `transcript.json` via Bitrix24 disk API and bind to the activity.
- On success: update `meta.json` `status → reporting`, then `→ reported`.
### Reports
- **Per-call:** `{UNIQUEID}/report_detail.html` — Jinja2 template; includes call metadata,
diarized transcript with emotion badges, script checklist table, score gauge.
- **Batch summary:** `reports/summary_{YYYY-MM-DD}.html` — aggregates calls in a configurable
window; metrics: call count, avg score, emotion distribution, compliance rate per agent.
- Report templates live in `reporter/templates/`. Do not hard-code HTML in Python.
---
## Configuration (`config.toml`)
All settings have documented defaults in `config/config.example.toml`.
Required fields that have no default will raise `ValidationError` on startup — check the log.
Key sections:
```toml
[storage]
spool_root = "/var/lib/voice-pipeline/spool"
db_url = "sqlite:////var/lib/voice-pipeline/db.sqlite3"
[schedule]
collect_interval = "5min" # systemd timer OnUnitActiveSec
[[sources.asterisk]]
transport = "sftp" # "sftp" | "http"
host = "pbx.example.com"
# ... credentials, path, filename_pattern
[sources.bitrix24]
webhook_url = "https://portal.bitrix24.ru/rest/1/xxxx/"
[llm]
backend = "cloud" # "cloud" | "local"
provider = "anthropic" # "anthropic" | "openai" (cloud only)
model = "claude-sonnet-4-6"
# local: ollama_url, model_name
[analyzer]
whisper_backend = "openai" # "openai" | "faster-whisper"
first_speaker_is_agent = true
emotion_backend = "transformers" # "transformers" | "llm"
```
---
## Development setup
```bash
# Create and activate venv
python3 -m venv .venv && source .venv/bin/activate
# Install with dev extras (src/ layout — no PYTHONPATH needed)
pip install -e ".[dev]"
# Add ML backends as needed:
# pip install -e ".[dev,cloud]" # OpenAI Whisper + Anthropic
# pip install -e ".[dev,local-asr]" # faster-whisper (local CPU/GPU)
# pip install -e ".[dev,diarize]" # pyannote (Bitrix24 diarization)
# pip install -e ".[dev,emotion]" # transformers emotion model
# pip install -e ".[local,dev]" # everything
# Copy and edit config
cp config/config.example.toml config/config.toml
export VOICE_PIPELINE_CONFIG=$(pwd)/config/config.toml
# Run a process manually via the installed CLI entry point
voice-pipeline collector
voice-pipeline analyzer
voice-pipeline reporter
# Validate config and connectivity
voice-pipeline validate-config
# Run tests (pythonpath = ["src"] set in pyproject.toml)
pytest tests/ -v
```
---
## Systemd deployment
```bash
# Run as root or with sudo
bash systemd/install.sh
# The install script:
# 1. Creates system user 'voice-pipeline' if absent
# 2. Copies unit files to /etc/systemd/system/
# 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-reporter.service
# Logs
journalctl -u voice-collector -f
journalctl -u voice-analyzer -f
journalctl -u voice-reporter -f
```
---
## Coding conventions
- Python 3.11+. Use `match`/`case` where it aids clarity.
- Type-annotate all public functions. Use `from __future__ import annotations`.
- Pydantic models for all data crossing process or I/O boundaries.
- `loguru` for all logging — never `print()`. Include `uniqueid=` in every log record touching a call.
- All external I/O (SFTP, HTTP, Bitrix24 API, LLM API) must be wrapped in retry logic
from `core/retry.py` (exponential backoff, configurable attempts).
- Tests use `pytest`. Fixtures for audio files live in `tests/fixtures/`.
Do not make real network calls in tests — mock at the transport layer.
- Format with `ruff format`, lint with `ruff check`. Config in `pyproject.toml`.
---
## Key constraints — do not violate
1. **`meta.json` is written last, atomically** (temp file → `os.rename`). This is the readiness signal.
2. **Never spool a partial 3-file set** from Asterisk. All 3 WAVs must be present and size-stable first.
3. **`rx.wav` = agent, `tx.wav` = customer** — this mapping is fixed and must never be reversed.
4. **LLM sees text only** — never pass audio to the LLM. Transcription always happens first.
5. **Status transitions are append-only** — never go backwards in the lifecycle.
6. **All processes run as `voice-pipeline` user** — no root privileges at runtime.

View File

@ -1 +0,0 @@
root@aihost.18091

View File

@ -0,0 +1 @@
root@aihost.18091

View File

@ -1,157 +1,157 @@
# voice-pipeline configuration
# Copy this file to /etc/voice-pipeline/config.toml and fill in your values.
# Set VOICE_PIPELINE_CONFIG env var to override the default path.
# ---------------------------------------------------------------------------
# Storage
# ---------------------------------------------------------------------------
[storage]
# Root directory for the spool (downloaded audio + metadata).
# Must be writable by the voice-pipeline system user.
spool_root = "/var/lib/voice-pipeline/spool"
# Root directory for generated HTML reports.
reports_root = "/var/lib/voice-pipeline/reports"
# SQLite DB (default) or PostgreSQL.
# PostgreSQL example: "postgresql+psycopg2://user:pass@localhost/voice_pipeline"
db_url = "sqlite:////var/lib/voice-pipeline/db.sqlite3"
# How many days to retain spool directories (future cleanup job).
retention_days = 30
# ---------------------------------------------------------------------------
# Schedule
# ---------------------------------------------------------------------------
[schedule]
# Passed verbatim to OnUnitActiveSec in voice-collector.timer.
# Examples: "5min", "15min", "1h"
collect_interval = "5min"
# Poll interval in seconds for the analyzer and reporter long-running services.
poll_interval_s = 10
# ---------------------------------------------------------------------------
# Sources — Asterisk (one [[sources.asterisk]] block per PBX)
# ---------------------------------------------------------------------------
[[sources.asterisk]]
# Friendly name for this source (used in logs).
name = "main-pbx"
# Transport: "sftp" or "http"
transport = "sftp"
# PBX hostname / IP
host = "pbx.example.com"
port = 22
# SFTP credentials — use ssh_key_path OR password, not both.
username = "asterisk-monitor"
# password = "secret"
ssh_key_path = "/var/lib/voice-pipeline/.ssh/id_rsa"
# Remote directory containing the WAV files.
remote_path = "/var/spool/asterisk/monitor"
# Regex to extract UNIQUEID from a filename.
# Must contain a named group `uid`.
# Default matches: 1701234567.42-mixed.wav
# 1701234567.42-rx-.wav
# 1701234567.42-tx-.wav
filename_pattern = '^(?P<uid>[\d.]+)-(mixed|rx-|tx-)\.wav$'
# Seconds to wait before re-measuring file sizes (stability check).
stability_wait_s = 5
# Max SFTP/HTTP retry attempts per file set.
retry_attempts = 3
retry_backoff_s = 2.0
# --- HTTP transport example (uncomment and set transport = "http") ---
# [[sources.asterisk]]
# name = "remote-pbx"
# transport = "http"
# base_url = "https://pbx2.example.com/recordings"
# http_token = "your-bearer-token"
# filename_pattern = '^(?P<uid>[\d.]+)-(mixed|rx-|tx-)\.wav$'
# ---------------------------------------------------------------------------
# Sources — Bitrix24 (optional; comment out the whole section to disable)
# ---------------------------------------------------------------------------
[sources.bitrix24]
# Bitrix24 REST webhook URL (includes user ID and auth token).
# Create one at: https://your-portal.bitrix24.ru/devops/list-webhooks/
webhook_url = "https://your-portal.bitrix24.ru/rest/1/your-token/"
# Number of activities to fetch per API page.
page_size = 50
retry_attempts = 3
retry_backoff_s = 2.0
# ---------------------------------------------------------------------------
# LLM
# ---------------------------------------------------------------------------
[llm]
# "cloud" → Anthropic or OpenAI API
# "local" → Ollama (runs locally, no API key needed)
backend = "cloud"
# Cloud provider: "anthropic" or "openai"
provider = "anthropic"
model = "claude-sonnet-4-6"
# API key — leave empty to use ANTHROPIC_API_KEY / OPENAI_API_KEY env var.
api_key = ""
# Local (Ollama) settings — used only when backend = "local"
ollama_url = "http://localhost:11434"
ollama_model = "llama3"
# Shared
max_tokens = 4096
temperature = 0.0
# How many times to retry a failed LLM call before marking the call failed.
llm_retry_attempts = 2
# ---------------------------------------------------------------------------
# Analyzer
# ---------------------------------------------------------------------------
[analyzer]
# Whisper backend: "openai" (cloud API) or "faster-whisper" (local GPU/CPU)
whisper_backend = "openai"
# OpenAI Whisper model name (used when whisper_backend = "openai")
whisper_model = "whisper-1"
# faster-whisper settings (used when whisper_backend = "faster-whisper")
faster_whisper_model = "large-v3"
faster_whisper_device = "cpu" # "cuda" for GPU
# For Bitrix24 calls (no rx/tx): map the first detected speaker to "agent".
first_speaker_is_agent = true
# Emotion backend: "transformers" (local HuggingFace) or "llm" (via LLM API)
emotion_backend = "transformers"
emotion_model = "j-hartmann/emotion-english-distilroberta-base"
# Script definition files (TOML format, relative to this config file's directory).
# script_files = ["scripts/inbound_v3.toml", "scripts/outbound_v1.toml"]
script_files = []
# ---------------------------------------------------------------------------
# Reporter
# ---------------------------------------------------------------------------
[reporter]
# Maximum characters for the transcript pasted into the Bitrix24 activity description.
bitrix_description_max_chars = 10000
# Days covered by each batch summary report.
summary_window_days = 1
# voice-pipeline configuration
# Copy this file to /etc/voice-pipeline/config.toml and fill in your values.
# Set VOICE_PIPELINE_CONFIG env var to override the default path.
# ---------------------------------------------------------------------------
# Storage
# ---------------------------------------------------------------------------
[storage]
# Root directory for the spool (downloaded audio + metadata).
# Must be writable by the voice-pipeline system user.
spool_root = "/var/lib/voice-pipeline/spool"
# Root directory for generated HTML reports.
reports_root = "/var/lib/voice-pipeline/reports"
# SQLite DB (default) or PostgreSQL.
# PostgreSQL example: "postgresql+psycopg2://user:pass@localhost/voice_pipeline"
db_url = "sqlite:////var/lib/voice-pipeline/db.sqlite3"
# How many days to retain spool directories (future cleanup job).
retention_days = 30
# ---------------------------------------------------------------------------
# Schedule
# ---------------------------------------------------------------------------
[schedule]
# Passed verbatim to OnUnitActiveSec in voice-collector.timer.
# Examples: "5min", "15min", "1h"
collect_interval = "5min"
# Poll interval in seconds for the analyzer and reporter long-running services.
poll_interval_s = 10
# ---------------------------------------------------------------------------
# Sources — Asterisk (one [[sources.asterisk]] block per PBX)
# ---------------------------------------------------------------------------
[[sources.asterisk]]
# Friendly name for this source (used in logs).
name = "main-pbx"
# Transport: "sftp" or "http"
transport = "sftp"
# PBX hostname / IP
host = "pbx.example.com"
port = 22
# SFTP credentials — use ssh_key_path OR password, not both.
username = "asterisk-monitor"
# password = "secret"
ssh_key_path = "/var/lib/voice-pipeline/.ssh/id_rsa"
# Remote directory containing the WAV files.
remote_path = "/var/spool/asterisk/monitor"
# Regex to extract UNIQUEID from a filename.
# Must contain a named group `uid`.
# Default matches: 1701234567.42-mixed.wav
# 1701234567.42-rx-.wav
# 1701234567.42-tx-.wav
filename_pattern = '^(?P<uid>[\d.]+)-(mixed|rx-|tx-)\.wav$'
# Seconds to wait before re-measuring file sizes (stability check).
stability_wait_s = 5
# Max SFTP/HTTP retry attempts per file set.
retry_attempts = 3
retry_backoff_s = 2.0
# --- HTTP transport example (uncomment and set transport = "http") ---
# [[sources.asterisk]]
# name = "remote-pbx"
# transport = "http"
# base_url = "https://pbx2.example.com/recordings"
# http_token = "your-bearer-token"
# filename_pattern = '^(?P<uid>[\d.]+)-(mixed|rx-|tx-)\.wav$'
# ---------------------------------------------------------------------------
# Sources — Bitrix24 (optional; comment out the whole section to disable)
# ---------------------------------------------------------------------------
[sources.bitrix24]
# Bitrix24 REST webhook URL (includes user ID and auth token).
# Create one at: https://your-portal.bitrix24.ru/devops/list-webhooks/
webhook_url = "https://your-portal.bitrix24.ru/rest/1/your-token/"
# Number of activities to fetch per API page.
page_size = 50
retry_attempts = 3
retry_backoff_s = 2.0
# ---------------------------------------------------------------------------
# LLM
# ---------------------------------------------------------------------------
[llm]
# "cloud" → Anthropic or OpenAI API
# "local" → Ollama (runs locally, no API key needed)
backend = "cloud"
# Cloud provider: "anthropic" or "openai"
provider = "anthropic"
model = "claude-sonnet-4-6"
# API key — leave empty to use ANTHROPIC_API_KEY / OPENAI_API_KEY env var.
api_key = ""
# Local (Ollama) settings — used only when backend = "local"
ollama_url = "http://localhost:11434"
ollama_model = "llama3"
# Shared
max_tokens = 4096
temperature = 0.0
# How many times to retry a failed LLM call before marking the call failed.
llm_retry_attempts = 2
# ---------------------------------------------------------------------------
# Analyzer
# ---------------------------------------------------------------------------
[analyzer]
# Whisper backend: "openai" (cloud API) or "faster-whisper" (local GPU/CPU)
whisper_backend = "openai"
# OpenAI Whisper model name (used when whisper_backend = "openai")
whisper_model = "whisper-1"
# faster-whisper settings (used when whisper_backend = "faster-whisper")
faster_whisper_model = "large-v3"
faster_whisper_device = "cpu" # "cuda" for GPU
# For Bitrix24 calls (no rx/tx): map the first detected speaker to "agent".
first_speaker_is_agent = true
# Emotion backend: "transformers" (local HuggingFace) or "llm" (via LLM API)
emotion_backend = "transformers"
emotion_model = "j-hartmann/emotion-english-distilroberta-base"
# Script definition files (TOML format, relative to this config file's directory).
# script_files = ["scripts/inbound_v3.toml", "scripts/outbound_v1.toml"]
script_files = []
# ---------------------------------------------------------------------------
# Reporter
# ---------------------------------------------------------------------------
[reporter]
# Maximum characters for the transcript pasted into the Bitrix24 activity description.
bitrix_description_max_chars = 10000
# Days covered by each batch summary report.
summary_window_days = 1

View File

@ -1,65 +1,65 @@
### CLI-команда
Команда `voice-pipeline reload` предназначена для перезагрузки файлов коллектором из источников и имеет три режима выполнения:
---
**Посмотреть** что есть в БД (без изменений):
```bash
# Все звонки за дату
voice-pipeline reload --list --date 2026-06-23
# Все failed
voice-pipeline reload --list --status failed
# Конкретный звонок
voice-pipeline reload --list --uniqueid 1782211489.118028
```
Вывод:
```
Found 47 call(s):
1782203663.115528 status=reported dir=inbound phone=89049536226 spool=/var/lib/voice-pipeline/spool/2026-06-23/1782203663.115528
1782211489.118028 status=failed dir=outbound phone=89874967783 spool=/var/lib/voice-pipeline/spool/2026-06-23/1782211489.118028
...
```
---
**Повторный анализ** (файлы уже скачаны, только сбросить статус):
```bash
# Один звонок
voice-pipeline reload --reanalyze --uniqueid 1782211489.118028
# Все failed звонки
voice-pipeline reload --reanalyze --status failed
# Вся дата
voice-pipeline reload --reanalyze --date 2026-06-23
```
Что делает: `status→spooled`, `failure_count→0`, чистит `last_error`, обновляет `meta.json`. Analyzer подхватит при следующем поллинге.
---
**Полная перезагрузка** (удалить и скачать заново с обогащением):
```bash
# Один звонок
voice-pipeline reload --recollect --uniqueid 1782211489.118028
# Вся дата
voice-pipeline reload --recollect --date 2026-06-23
```
Что делает: удаляет spool-каталог + записи из `call_records` и `analysis_artifacts`. Следующий запуск коллектора скачает файлы заново с чистым Bitrix24-обогащением.
---
Оба режима спрашивают подтверждение:
```
Action: reanalyze on 47 call(s)
Proceed? [y/N]
```
### CLI-команда
Команда `voice-pipeline reload` предназначена для перезагрузки файлов коллектором из источников и имеет три режима выполнения:
---
**Посмотреть** что есть в БД (без изменений):
```bash
# Все звонки за дату
voice-pipeline reload --list --date 2026-06-23
# Все failed
voice-pipeline reload --list --status failed
# Конкретный звонок
voice-pipeline reload --list --uniqueid 1782211489.118028
```
Вывод:
```
Found 47 call(s):
1782203663.115528 status=reported dir=inbound phone=89049536226 spool=/var/lib/voice-pipeline/spool/2026-06-23/1782203663.115528
1782211489.118028 status=failed dir=outbound phone=89874967783 spool=/var/lib/voice-pipeline/spool/2026-06-23/1782211489.118028
...
```
---
**Повторный анализ** (файлы уже скачаны, только сбросить статус):
```bash
# Один звонок
voice-pipeline reload --reanalyze --uniqueid 1782211489.118028
# Все failed звонки
voice-pipeline reload --reanalyze --status failed
# Вся дата
voice-pipeline reload --reanalyze --date 2026-06-23
```
Что делает: `status→spooled`, `failure_count→0`, чистит `last_error`, обновляет `meta.json`. Analyzer подхватит при следующем поллинге.
---
**Полная перезагрузка** (удалить и скачать заново с обогащением):
```bash
# Один звонок
voice-pipeline reload --recollect --uniqueid 1782211489.118028
# Вся дата
voice-pipeline reload --recollect --date 2026-06-23
```
Что делает: удаляет spool-каталог + записи из `call_records` и `analysis_artifacts`. Следующий запуск коллектора скачает файлы заново с чистым Bitrix24-обогащением.
---
Оба режима спрашивают подтверждение:
```
Action: reanalyze on 47 call(s)
Proceed? [y/N]
```

View File

@ -1,89 +1,91 @@
[build-system]
requires = ["setuptools>=68", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "voice-pipeline"
version = "0.1.0"
requires-python = ">=3.11"
# Core runtime — always installed. Heavy ML extras are optional (see below).
dependencies = [
# transport
"paramiko>=3.4",
"httpx>=0.27",
# audio
"pydub>=0.25",
# config + validation
"pydantic>=2.7",
"pydantic-settings>=2.3",
# ORM / DB
"sqlmodel>=0.0.19",
# logging
"loguru>=0.7",
# templating (reporter)
"jinja2>=3.1",
# anthropic LLM (script checking)
"anthropic>=0.28",
]
[project.optional-dependencies]
# Cloud transcription only (no local models)
[build-system]
requires = ["setuptools>=68", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "voice-pipeline"
version = "0.1.0"
requires-python = ">=3.11"
# Core runtime — always installed. Heavy ML extras are optional (see below).
dependencies = [
# transport
"paramiko>=3.4",
"httpx>=0.27",
# audio
"pydub>=0.25",
# config + validation
"pydantic>=2.7",
"pydantic-settings>=2.3",
# ORM / DB
"sqlmodel>=0.0.19",
# logging
"loguru>=0.7",
# templating (reporter)
"jinja2>=3.1",
# anthropic LLM (script checking)
"anthropic>=0.28",
]
[project.optional-dependencies]
# Cloud transcription only (no local models)
cloud = [
"openai>=1.30",
"groq>=0.11",
]
# Local transcription on CPU/GPU
local-asr = [
"faster-whisper>=1.0",
]
# Bitrix24-source diarization fallback (needs HF token)
diarize = [
"pyannote.audio>=3.1",
]
# Local emotion classification
emotion = [
"transformers>=4.40",
"torch>=2.2",
]
# Everything local (CPU) — equivalent to all optional groups above
local = [
"voice-pipeline[cloud,local-asr,diarize,emotion]",
]
# Development tools
dev = [
"pytest>=8.2",
"pytest-asyncio>=0.23",
"pytest-mock>=3.14",
"ruff>=0.4",
"mypy>=1.10",
]
# Minimal install for dev/testing without ML models
dev-only = [
"voice-pipeline[dev]",
]
[project.scripts]
voice-pipeline = "voice_pipeline.__main__:main"
[tool.setuptools.packages.find]
where = ["src"]
include = ["voice_pipeline*", "collector*", "analyzer*", "reporter*", "core*"]
[tool.ruff]
line-length = 100
target-version = "py311"
# Local transcription on CPU/GPU
local-asr = [
"faster-whisper>=1.0",
]
# Bitrix24-source diarization fallback (needs HF token)
diarize = [
"pyannote.audio>=3.1",
]
# Local emotion classification
emotion = [
"transformers>=4.40",
"torch>=2.2",
]
# Everything local (CPU) — equivalent to all optional groups above
local = [
"voice-pipeline[cloud,local-asr,diarize,emotion]",
]
# Development tools
dev = [
"pytest>=8.2",
"pytest-asyncio>=0.23",
"pytest-mock>=3.14",
"ruff>=0.4",
"mypy>=1.10",
]
# Minimal install for dev/testing without ML models
dev-only = [
"voice-pipeline[dev]",
]
[project.scripts]
voice-pipeline = "voice_pipeline.__main__:main"
[tool.setuptools.packages.find]
where = ["src"]
include = ["voice_pipeline*", "collector*", "analyzer*", "reporter*", "core*"]
[tool.ruff]
line-length = 100
target-version = "py311"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "SIM"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
pythonpath = ["src"]
ignore = ["E402"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
pythonpath = ["src"]

4
pyrightconfig.json Normal file
View File

@ -0,0 +1,4 @@
{
"reportMissingImports": "none",
"reportMissingModuleSource": "none"
}

View File

@ -1,162 +1,162 @@
# scripts/ — Call compliance script definitions
Each `.toml` file in this directory defines one compliance script.
The analyzer loads whichever files are listed in `config.toml` under
`[analyzer] script_files`.
---
## Registering scripts in config.toml
```toml
[analyzer]
script_files = [
"scripts/inbound_support.toml",
"scripts/outbound_sales.toml",
]
```
Paths are resolved relative to the config file's directory.
Absolute paths also work.
When a call arrives, `analyzer.script_check.select_script()` picks the
**first** script whose `directions` list contains the call's direction
(`"inbound"`, `"outbound"`, or `"unknown"`).
Order the list with your most specific scripts first.
---
## TOML schema
```toml
# Required
script_id = "unique_snake_case_id" # used in analysis.json artifacts
name = "Human-readable name" # shown in HTML reports
# Which call directions this script applies to.
# Values: "inbound" | "outbound" | "unknown"
# "unknown" catches Asterisk calls where direction was not detected.
directions = ["inbound"]
# One [[checklist]] block per item.
[[checklist]]
item = "Short label (shown in report and passed to LLM)"
description = """
Optional. Longer guidance for the LLM explaining what evidence to look
for and how to judge this item. Wrap in triple-quotes for multi-line.
Mark critical items with КРИТИЧНО / CRITICAL in the description —
the LLM scoring prompt instructs it to weight described items more heavily.
"""
```
### Field reference
| Field | Required | Notes |
| ------------------------- | -------- | --------------------------------------------------------------------------------------------- |
| `script_id` | yes | Unique. Used as the key in `analysis.json`. Changing it breaks historical report comparisons. |
| `name` | no | Defaults to `script_id`. Shown in HTML reports. |
| `directions` | no | Defaults to `["inbound", "outbound"]` (matches all calls). |
| `checklist[].item` | yes | Short, unambiguous label. The LLM copies this verbatim into its JSON response. |
| `checklist[].description` | no | Detailed guidance for the LLM. Has no effect on the report UI — for LLM accuracy only. |
---
## Included scripts
| File | `script_id` | Directions | Items |
| ---------------------- | -------------------- | ---------------- | ----- |
| `inbound_support.toml` | `inbound_support_v1` | inbound, unknown | 11 |
| `outbound_sales.toml` | `outbound_sales_v1` | outbound | 12 |
### inbound_support_v1 — item summary
| # | Item | Critical |
| --- | ------------------------------------------------------------------- | -------- |
| 1 | Приветствие с названием компании / Greeting with company name | ✓ |
| 2 | Представление оператора / Agent self-introduction | |
| 3 | Предложение помощи / Offer of assistance | |
| 4 | Уточнение имени клиента / Asking customer's name | |
| 5 | Выяснение сути обращения / Understanding the issue | |
| 6 | Подтверждение понимания / Confirming understanding | |
| 7 | Решение вопроса или эскалация / Issue resolved or escalated | ✓ |
| 8 | Информирование о сроках / Timeline or next step communicated | |
| 9 | Проверка удовлетворённости клиента / Checking customer satisfaction | |
| 10 | Благодарность за обращение / Thanking the customer | |
| 11 | Прощание / Farewell | |
| 12 | Отсутствие грубости или раздражения / No rudeness or irritation | |
| 13 | Чёткость и понятность речи / Clear and understandable speech | |
### outbound_sales_v1 — item summary
| # | Item | Critical |
| --- | -------------------------------------------------------------------------------------- | -------- |
| 1 | Представление агента и компании / Agent and company introduction | ✓ |
| 2 | Проверка удобства разговора / Checking if it's a good time | |
| 3 | Чёткое обозначение цели звонка / Clear statement of call purpose | |
| 4 | Квалификация клиента / Customer qualification | |
| 5 | Выявление потребности / Identifying a pain point or need | |
| 6 | Презентация под потребность клиента / Tailored value proposition | |
| 7 | Упоминание ключевого УТП или выгоды / Key differentiator or benefit stated | |
| 8 | Работа с возражением / Handling at least one objection | ✓ |
| 9 | Отсутствие давления или спора / No pressure tactics or arguing | |
| 10 | Попытка закрытия или фиксация следующего шага / Closing attempt or next-step agreement | ✓ |
| 11 | Подтверждение договорённостей / Confirming what was agreed | |
| 12 | Вежливое завершение звонка / Polite closing | |
| 13 | Соблюдение регламента в отношении записи / Compliance with call recording notice | |
| 14 | Профессиональный тон на протяжении звонка / Professional tone throughout | |
---
## Versioning
When you revise a script, increment the version suffix in `script_id`
(`v1` → `v2`) and add the new file to `script_files` instead of editing
the existing one. Historical `analysis.json` artifacts embed the
`script_id` they were evaluated against, so old reports remain comparable.
```toml
# config.toml — keep both versions so you can compare
[analyzer]
script_files = [
"scripts/inbound_support_v2.toml", # new calls
"scripts/outbound_sales.toml",
]
```
---
## Writing a new script
1. Copy `inbound_support.toml` as a starting point.
2. Set a unique `script_id` and the correct `directions`.
3. Write checklist items as **observable, verifiable behaviours** — things
the LLM can confirm from the transcript text.
- Good: `"Agent stated the customer's name at least once"`
- Bad: `"Agent was empathetic"` (too subjective, low LLM accuracy)
4. Mark 2–4 items as `КРИТИЧНО / CRITICAL` in their `description`.
These anchor the scoring — if any critical item fails, the score
should not exceed ~70 regardless of the rest.
5. Keep the total checklist under 15 items. Beyond that, LLM accuracy
on individual items degrades and scores become noisy.
6. Register the file in `config.toml` and run a test call through the
analyzer to verify the output shape.
---
## Testing a script without real calls
Use the integration test fixture:
```python
# tests/test_integration.py already patches call_llm_json.
# To test your script parsing specifically, run:
from analyzer.script_check import load_script_definitions, select_script
import os
os.environ["VOICE_PIPELINE_CONFIG"] = "config/config.toml"
definitions = load_script_definitions()
for d in definitions:
print(d.script_id, d.directions, len(d.checklist), "items")
```
# scripts/ — Call compliance script definitions
Each `.toml` file in this directory defines one compliance script.
The analyzer loads whichever files are listed in `config.toml` under
`[analyzer] script_files`.
---
## Registering scripts in config.toml
```toml
[analyzer]
script_files = [
"scripts/inbound_support.toml",
"scripts/outbound_sales.toml",
]
```
Paths are resolved relative to the config file's directory.
Absolute paths also work.
When a call arrives, `analyzer.script_check.select_script()` picks the
**first** script whose `directions` list contains the call's direction
(`"inbound"`, `"outbound"`, or `"unknown"`).
Order the list with your most specific scripts first.
---
## TOML schema
```toml
# Required
script_id = "unique_snake_case_id" # used in analysis.json artifacts
name = "Human-readable name" # shown in HTML reports
# Which call directions this script applies to.
# Values: "inbound" | "outbound" | "unknown"
# "unknown" catches Asterisk calls where direction was not detected.
directions = ["inbound"]
# One [[checklist]] block per item.
[[checklist]]
item = "Short label (shown in report and passed to LLM)"
description = """
Optional. Longer guidance for the LLM explaining what evidence to look
for and how to judge this item. Wrap in triple-quotes for multi-line.
Mark critical items with КРИТИЧНО / CRITICAL in the description —
the LLM scoring prompt instructs it to weight described items more heavily.
"""
```
### Field reference
| Field | Required | Notes |
| ------------------------- | -------- | --------------------------------------------------------------------------------------------- |
| `script_id` | yes | Unique. Used as the key in `analysis.json`. Changing it breaks historical report comparisons. |
| `name` | no | Defaults to `script_id`. Shown in HTML reports. |
| `directions` | no | Defaults to `["inbound", "outbound"]` (matches all calls). |
| `checklist[].item` | yes | Short, unambiguous label. The LLM copies this verbatim into its JSON response. |
| `checklist[].description` | no | Detailed guidance for the LLM. Has no effect on the report UI — for LLM accuracy only. |
---
## Included scripts
| File | `script_id` | Directions | Items |
| ---------------------- | -------------------- | ---------------- | ----- |
| `inbound_support.toml` | `inbound_support_v1` | inbound, unknown | 11 |
| `outbound_sales.toml` | `outbound_sales_v1` | outbound | 12 |
### inbound_support_v1 — item summary
| # | Item | Critical |
| --- | ------------------------------------------------------------------- | -------- |
| 1 | Приветствие с названием компании / Greeting with company name | ✓ |
| 2 | Представление оператора / Agent self-introduction | |
| 3 | Предложение помощи / Offer of assistance | |
| 4 | Уточнение имени клиента / Asking customer's name | |
| 5 | Выяснение сути обращения / Understanding the issue | |
| 6 | Подтверждение понимания / Confirming understanding | |
| 7 | Решение вопроса или эскалация / Issue resolved or escalated | ✓ |
| 8 | Информирование о сроках / Timeline or next step communicated | |
| 9 | Проверка удовлетворённости клиента / Checking customer satisfaction | |
| 10 | Благодарность за обращение / Thanking the customer | |
| 11 | Прощание / Farewell | |
| 12 | Отсутствие грубости или раздражения / No rudeness or irritation | |
| 13 | Чёткость и понятность речи / Clear and understandable speech | |
### outbound_sales_v1 — item summary
| # | Item | Critical |
| --- | -------------------------------------------------------------------------------------- | -------- |
| 1 | Представление агента и компании / Agent and company introduction | ✓ |
| 2 | Проверка удобства разговора / Checking if it's a good time | |
| 3 | Чёткое обозначение цели звонка / Clear statement of call purpose | |
| 4 | Квалификация клиента / Customer qualification | |
| 5 | Выявление потребности / Identifying a pain point or need | |
| 6 | Презентация под потребность клиента / Tailored value proposition | |
| 7 | Упоминание ключевого УТП или выгоды / Key differentiator or benefit stated | |
| 8 | Работа с возражением / Handling at least one objection | ✓ |
| 9 | Отсутствие давления или спора / No pressure tactics or arguing | |
| 10 | Попытка закрытия или фиксация следующего шага / Closing attempt or next-step agreement | ✓ |
| 11 | Подтверждение договорённостей / Confirming what was agreed | |
| 12 | Вежливое завершение звонка / Polite closing | |
| 13 | Соблюдение регламента в отношении записи / Compliance with call recording notice | |
| 14 | Профессиональный тон на протяжении звонка / Professional tone throughout | |
---
## Versioning
When you revise a script, increment the version suffix in `script_id`
(`v1` → `v2`) and add the new file to `script_files` instead of editing
the existing one. Historical `analysis.json` artifacts embed the
`script_id` they were evaluated against, so old reports remain comparable.
```toml
# config.toml — keep both versions so you can compare
[analyzer]
script_files = [
"scripts/inbound_support_v2.toml", # new calls
"scripts/outbound_sales.toml",
]
```
---
## Writing a new script
1. Copy `inbound_support.toml` as a starting point.
2. Set a unique `script_id` and the correct `directions`.
3. Write checklist items as **observable, verifiable behaviours** — things
the LLM can confirm from the transcript text.
- Good: `"Agent stated the customer's name at least once"`
- Bad: `"Agent was empathetic"` (too subjective, low LLM accuracy)
4. Mark 2–4 items as `КРИТИЧНО / CRITICAL` in their `description`.
These anchor the scoring — if any critical item fails, the score
should not exceed ~70 regardless of the rest.
5. Keep the total checklist under 15 items. Beyond that, LLM accuracy
on individual items degrades and scores become noisy.
6. Register the file in `config.toml` and run a test call through the
analyzer to verify the output shape.
---
## Testing a script without real calls
Use the integration test fixture:
```python
# tests/test_integration.py already patches call_llm_json.
# To test your script parsing specifically, run:
from analyzer.script_check import load_script_definitions, select_script
import os
os.environ["VOICE_PIPELINE_CONFIG"] = "config/config.toml"
definitions = load_script_definitions()
for d in definitions:
print(d.script_id, d.directions, len(d.checklist), "items")
```

View File

@ -1,155 +1,155 @@
# scripts/inbound_support.toml
#
# Script definition for inbound customer support / service calls.
# Used by analyzer.script_check to evaluate agent compliance.
#
# Directions: this script is applied to calls classified as "inbound".
# Add "unknown" to directions if calls from Asterisk sometimes arrive
# without a direction field.
#
# Scoring guide (from the LLM system prompt):
# Each missed item deducts proportionally. Critical items (marked with
# a description containing "КРИТИЧНО" / "CRITICAL") carry more weight —
# the LLM is instructed to weigh described items more heavily.
#
# To activate: add this file's path to config.toml:
# [analyzer]
# script_files = ["scripts/inbound_support.toml"]
script_id = "inbound_support_v1"
name = "Входящий звонок — поддержка / Inbound support call"
directions = ["inbound", "unknown"]
# ── Раздел 1 / Section 1: Opening ─────────────────────────────────────────
#
# The first 30 seconds set the customer's perception of the whole call.
# All three items here are required; missing any one of them sharply
# reduces the score.
[[checklist]]
item = "Приветствие с названием компании / Greeting with company name"
description = """
КРИТИЧНО. Агент должен поприветствовать клиента и назвать компанию в первых
двух фразах. Примеры: «Добрый день, компания Ромашка», «Здравствуйте, вы
позвонили в Ромашка». / CRITICAL. Agent must greet the caller and name the
company within the first two utterances.
"""
[[checklist]]
item = "Представление оператора / Agent self-introduction"
description = """
Агент называет своё имя. Пример: «меня зовут Анна», «это Дмитрий». /
Agent states their first name. Example: 'my name is Anna', 'this is Dmitry'.
"""
[[checklist]]
item = "Предложение помощи / Offer of assistance"
description = """
Агент предлагает помощь открытой фразой. Примеры: «Чем могу помочь?»,
«Как я могу вам помочь сегодня?», 'How can I help you today?'
"""
# ── Раздел 2 / Section 2: Needs identification ────────────────────────────
[[checklist]]
item = "Уточнение имени клиента / Asking customer's name"
description = """
Агент спрашивает имя клиента, если оно не было озвучено клиентом самостоятельно.
Пример: «Как я могу к вам обращаться?», 'May I have your name?' Допускается
пропуск, если клиент сам представился в начале. /
Agent asks for the customer's name unless the customer volunteered it.
"""
[[checklist]]
item = "Выяснение сути обращения / Understanding the issue"
description = """
Агент даёт клиенту возможность полностью изложить проблему, задаёт
уточняющие вопросы при необходимости. Не перебивает до того, как клиент
закончил. / Agent lets the customer explain the issue fully and asks
clarifying questions as needed without interrupting prematurely.
"""
[[checklist]]
item = "Подтверждение понимания / Confirming understanding"
description = """
Агент кратко повторяет суть вопроса клиента, чтобы убедиться в правильном
понимании. Пример: «Правильно ли я понимаю, что…», 'So if I understand
correctly, you're saying that…' / Agent paraphrases the customer's issue
back to confirm understanding.
"""
# ── Раздел 3 / Section 3: Resolution ──────────────────────────────────────
[[checklist]]
item = "Решение вопроса или эскалация / Issue resolved or escalated"
description = """
КРИТИЧНО. Агент либо решает вопрос клиента, либо явно сообщает о передаче
специалисту с объяснением причины. Недопустимо завершать звонок без результата.
/ CRITICAL. Agent either resolves the issue or explicitly transfers to a
specialist with a clear reason. Ending without outcome is not acceptable.
"""
[[checklist]]
item = "Информирование о сроках / Timeline or next step communicated"
description = """
Если вопрос не решён немедленно, агент называет конкретный срок или следующий
шаг. Пример: «Мы свяжемся с вами в течение 24 часов», 'You'll receive a
confirmation email within one business day.' /
If not resolved immediately, agent states a specific timeframe or next step.
"""
[[checklist]]
item = "Проверка удовлетворённости клиента / Checking customer satisfaction"
description = """
Агент спрашивает, решён ли вопрос или остались ли ещё вопросы. Пример:
«Смогли ли мы решить ваш вопрос?», «Есть ли у вас ещё вопросы?»,
'Is there anything else I can help you with?' /
Agent checks whether the issue is resolved and whether the customer has
further questions.
"""
# ── Раздел 4 / Section 4: Closing ─────────────────────────────────────────
[[checklist]]
item = "Благодарность за обращение / Thanking the customer"
description = """
Агент благодарит клиента за звонок. Пример: «Спасибо за ваш звонок»,
«Благодарим за обращение в компанию Ромашка», 'Thank you for calling.' /
Agent thanks the customer for calling.
"""
[[checklist]]
item = "Прощание / Farewell"
description = """
Агент завершает звонок вежливой прощальной фразой. Пример: «Всего доброго»,
«Хорошего дня», 'Have a great day', 'Goodbye.' Агент не бросает трубку
без прощания. / Agent closes with a polite farewell and does not hang up
abruptly.
"""
# ── Раздел 5 / Section 5: Quality & tone ──────────────────────────────────
#
# These items are evaluated qualitatively across the whole call.
# The LLM uses the full transcript to judge them.
[[checklist]]
item = "Отсутствие грубости или раздражения / No rudeness or irritation"
description = """
На протяжении всего разговора агент сохраняет спокойный и уважительный тон,
не перебивает клиента с раздражением, не использует пренебрежительных
выражений. / Throughout the call the agent maintains a calm, respectful tone
and does not use dismissive or irritated language.
"""
[[checklist]]
item = "Чёткость и понятность речи / Clear and understandable speech"
description = """
Агент говорит чётко, избегает чрезмерного использования жаргона, сложных
аббревиатур без расшифровки, не тараторит. / Agent speaks clearly, avoids
unexplained jargon or acronyms, and does not rush.
# scripts/inbound_support.toml
#
# Script definition for inbound customer support / service calls.
# Used by analyzer.script_check to evaluate agent compliance.
#
# Directions: this script is applied to calls classified as "inbound".
# Add "unknown" to directions if calls from Asterisk sometimes arrive
# without a direction field.
#
# Scoring guide (from the LLM system prompt):
# Each missed item deducts proportionally. Critical items (marked with
# a description containing "КРИТИЧНО" / "CRITICAL") carry more weight —
# the LLM is instructed to weigh described items more heavily.
#
# To activate: add this file's path to config.toml:
# [analyzer]
# script_files = ["scripts/inbound_support.toml"]
script_id = "inbound_support_v1"
name = "Входящий звонок — поддержка / Inbound support call"
directions = ["inbound", "unknown"]
# ── Раздел 1 / Section 1: Opening ─────────────────────────────────────────
#
# The first 30 seconds set the customer's perception of the whole call.
# All three items here are required; missing any one of them sharply
# reduces the score.
[[checklist]]
item = "Приветствие с названием компании / Greeting with company name"
description = """
КРИТИЧНО. Агент должен поприветствовать клиента и назвать компанию в первых
двух фразах. Примеры: «Добрый день, компания Ромашка», «Здравствуйте, вы
позвонили в Ромашка». / CRITICAL. Agent must greet the caller and name the
company within the first two utterances.
"""
[[checklist]]
item = "Представление оператора / Agent self-introduction"
description = """
Агент называет своё имя. Пример: «меня зовут Анна», «это Дмитрий». /
Agent states their first name. Example: 'my name is Anna', 'this is Dmitry'.
"""
[[checklist]]
item = "Предложение помощи / Offer of assistance"
description = """
Агент предлагает помощь открытой фразой. Примеры: «Чем могу помочь?»,
«Как я могу вам помочь сегодня?», 'How can I help you today?'
"""
# ── Раздел 2 / Section 2: Needs identification ────────────────────────────
[[checklist]]
item = "Уточнение имени клиента / Asking customer's name"
description = """
Агент спрашивает имя клиента, если оно не было озвучено клиентом самостоятельно.
Пример: «Как я могу к вам обращаться?», 'May I have your name?' Допускается
пропуск, если клиент сам представился в начале. /
Agent asks for the customer's name unless the customer volunteered it.
"""
[[checklist]]
item = "Выяснение сути обращения / Understanding the issue"
description = """
Агент даёт клиенту возможность полностью изложить проблему, задаёт
уточняющие вопросы при необходимости. Не перебивает до того, как клиент
закончил. / Agent lets the customer explain the issue fully and asks
clarifying questions as needed without interrupting prematurely.
"""
[[checklist]]
item = "Подтверждение понимания / Confirming understanding"
description = """
Агент кратко повторяет суть вопроса клиента, чтобы убедиться в правильном
понимании. Пример: «Правильно ли я понимаю, что…», 'So if I understand
correctly, you're saying that…' / Agent paraphrases the customer's issue
back to confirm understanding.
"""
# ── Раздел 3 / Section 3: Resolution ──────────────────────────────────────
[[checklist]]
item = "Решение вопроса или эскалация / Issue resolved or escalated"
description = """
КРИТИЧНО. Агент либо решает вопрос клиента, либо явно сообщает о передаче
специалисту с объяснением причины. Недопустимо завершать звонок без результата.
/ CRITICAL. Agent either resolves the issue or explicitly transfers to a
specialist with a clear reason. Ending without outcome is not acceptable.
"""
[[checklist]]
item = "Информирование о сроках / Timeline or next step communicated"
description = """
Если вопрос не решён немедленно, агент называет конкретный срок или следующий
шаг. Пример: «Мы свяжемся с вами в течение 24 часов», 'You'll receive a
confirmation email within one business day.' /
If not resolved immediately, agent states a specific timeframe or next step.
"""
[[checklist]]
item = "Проверка удовлетворённости клиента / Checking customer satisfaction"
description = """
Агент спрашивает, решён ли вопрос или остались ли ещё вопросы. Пример:
«Смогли ли мы решить ваш вопрос?», «Есть ли у вас ещё вопросы?»,
'Is there anything else I can help you with?' /
Agent checks whether the issue is resolved and whether the customer has
further questions.
"""
# ── Раздел 4 / Section 4: Closing ─────────────────────────────────────────
[[checklist]]
item = "Благодарность за обращение / Thanking the customer"
description = """
Агент благодарит клиента за звонок. Пример: «Спасибо за ваш звонок»,
«Благодарим за обращение в компанию Ромашка», 'Thank you for calling.' /
Agent thanks the customer for calling.
"""
[[checklist]]
item = "Прощание / Farewell"
description = """
Агент завершает звонок вежливой прощальной фразой. Пример: «Всего доброго»,
«Хорошего дня», 'Have a great day', 'Goodbye.' Агент не бросает трубку
без прощания. / Agent closes with a polite farewell and does not hang up
abruptly.
"""
# ── Раздел 5 / Section 5: Quality & tone ──────────────────────────────────
#
# These items are evaluated qualitatively across the whole call.
# The LLM uses the full transcript to judge them.
[[checklist]]
item = "Отсутствие грубости или раздражения / No rudeness or irritation"
description = """
На протяжении всего разговора агент сохраняет спокойный и уважительный тон,
не перебивает клиента с раздражением, не использует пренебрежительных
выражений. / Throughout the call the agent maintains a calm, respectful tone
and does not use dismissive or irritated language.
"""
[[checklist]]
item = "Чёткость и понятность речи / Clear and understandable speech"
description = """
Агент говорит чётко, избегает чрезмерного использования жаргона, сложных
аббревиатур без расшифровки, не тараторит. / Agent speaks clearly, avoids
unexplained jargon or acronyms, and does not rush.
"""

View File

@ -1,175 +1,175 @@
# scripts/outbound_sales.toml
#
# Script definition for outbound sales calls (cold calls, warm leads,
# follow-ups, upsell / cross-sell calls).
#
# Directions: "outbound" only — inbound calls use inbound_support.toml.
#
# Scoring note:
# Objection handling and closing attempt are the highest-weight items
# for a sales call. Both are marked КРИТИЧНО / CRITICAL.
#
# To activate alongside the inbound script:
# [analyzer]
# script_files = [
# "scripts/inbound_support.toml",
# "scripts/outbound_sales.toml",
# ]
script_id = "outbound_sales_v1"
name = "Исходящий звонок — продажи / Outbound sales call"
directions = ["outbound"]
# ── Раздел 1 / Section 1: Opening ─────────────────────────────────────────
[[checklist]]
item = "Представление агента и компании / Agent and company introduction"
description = """
КРИТИЧНО. Агент называет своё имя и компанию в самом начале звонка, до того
как перейти к цели. Пример: «Здравствуйте, меня зовут Иван, я из компании
Ромашка». / CRITICAL. Agent states their name and company at the very start,
before stating the purpose. Example: 'Hi, my name is Ivan calling from
Romashka.'
"""
[[checklist]]
item = "Проверка удобства разговора / Checking if it's a good time"
description = """
Агент спрашивает, удобно ли клиенту говорить прямо сейчас. Пример: «Удобно
ли вам сейчас разговаривать?», 'Is this a good time to talk?' Допускается
пропуск, если клиент сам вступил в разговор активно. /
Agent asks whether it's convenient to speak. May be omitted if the customer
immediately engages enthusiastically.
"""
[[checklist]]
item = "Чёткое обозначение цели звонка / Clear statement of call purpose"
description = """
Агент объясняет, по какому поводу звонит, в первые 30 секунд. Пример:
«Я звоню, чтобы рассказать о нашем новом предложении для постоянных
клиентов», 'I'm calling today because we have a special offer for existing
customers like yourself.' /
Agent states the reason for the call within the first 30 seconds.
"""
# ── Раздел 2 / Section 2: Qualification & needs ───────────────────────────
[[checklist]]
item = "Квалификация клиента / Customer qualification"
description = """
Агент задаёт уточняющие вопросы, чтобы понять, актуально ли предложение для
данного клиента (бюджет, полномочия, потребность, сроки). Пример: «Вы сейчас
пользуетесь подобным решением?», 'Are you currently using any similar
product?' / Agent asks discovery questions to gauge fit (budget, authority,
need, timeline).
"""
[[checklist]]
item = "Выявление потребности / Identifying a pain point or need"
description = """
Агент выявляет конкретную потребность или проблему клиента перед
презентацией. Не переходит к описанию продукта, не услышав о ситуации
клиента. / Agent uncovers a specific need or pain point before pitching.
Does not launch into a product description without first listening.
"""
# ── Раздел 3 / Section 3: Presentation ────────────────────────────────────
[[checklist]]
item = "Презентация под потребность клиента / Tailored value proposition"
description = """
Агент связывает характеристики продукта / услуги с конкретной потребностью,
озвученной клиентом. Не читает универсальный скрипт. Пример: «Учитывая то,
что вы сказали о сроках доставки, нам подойдёт вариант X, потому что…» /
Agent ties product features to the specific need the customer expressed.
Does not recite a generic pitch.
"""
[[checklist]]
item = "Упоминание ключевого УТП или выгоды / Key differentiator or benefit stated"
description = """
Агент явно называет одно или несколько конкурентных преимуществ или выгод.
Пример: «Мы единственные, кто предлагает гарантию возврата в течение 60
дней», 'One thing that sets us apart is the 60-day money-back guarantee.' /
Agent explicitly names at least one differentiator or concrete benefit.
"""
# ── Раздел 4 / Section 4: Objection handling ──────────────────────────────
[[checklist]]
item = "Работа с возражением / Handling at least one objection"
description = """
КРИТИЧНО. Если клиент высказывает возражение (цена, время, необходимость,
конкурент), агент его отрабатывает: выслушивает, уточняет, приводит аргумент
или альтернативу. Не капитулирует при первом возражении. /
CRITICAL. If the customer raises an objection (price, timing, need,
competitor), the agent handles it: acknowledges, clarifies, and responds
with an argument or alternative. Does not give up at the first pushback.
"""
[[checklist]]
item = "Отсутствие давления или спора / No pressure tactics or arguing"
description = """
Агент не спорит с клиентом, не использует давление или манипуляции, не
повторяет одни и те же аргументы более двух раз подряд. /
Agent does not argue with the customer, does not use high-pressure tactics,
and does not repeat the same argument more than twice in a row.
"""
# ── Раздел 5 / Section 5: Closing ─────────────────────────────────────────
[[checklist]]
item = "Попытка закрытия или фиксация следующего шага / Closing attempt or next-step agreement"
description = """
КРИТИЧНО. Агент делает явную попытку закрыть сделку (запрос на покупку,
согласование встречи, подтверждение заявки) или договаривается о конкретном
следующем шаге с датой. Звонок не может завершиться без конкретного итога. /
CRITICAL. Agent makes an explicit close attempt (purchase request, meeting
booking, application confirmation) or agrees on a specific next step with a
date. The call must not end without a concrete outcome.
"""
[[checklist]]
item = "Подтверждение договорённостей / Confirming what was agreed"
description = """
Агент кратко повторяет, что было согласовано: дату, сумму, следующий шаг.
Пример: «Итак, мы договорились, что я пришлю вам коммерческое предложение
до пятницы», 'So we've agreed I'll send you the proposal by Friday.' /
Agent summarises what was agreed: date, amount, or next step.
"""
[[checklist]]
item = "Вежливое завершение звонка / Polite closing"
description = """
Агент благодарит клиента за уделённое время и прощается. Пример: «Спасибо
за ваше время, всего доброго!», 'Thank you for your time — have a great day!'
/ Agent thanks the customer for their time and says a warm goodbye.
"""
# ── Раздел 6 / Section 6: Quality & compliance ────────────────────────────
[[checklist]]
item = "Соблюдение регламента в отношении записи / Compliance with call recording notice"
description = """
Если в компании принято уведомлять клиента о записи разговора, агент
произносит соответствующую фразу в начале звонка. Пропускается, если
уведомление воспроизводится автоматически. /
If company policy requires informing the customer that the call is recorded,
agent states this at the start. May be skipped if an automated recording
notice plays before the agent speaks.
"""
[[checklist]]
item = "Профессиональный тон на протяжении звонка / Professional tone throughout"
description = """
Агент поддерживает позитивный, уверенный и уважительный тон. Не проявляет
нетерпения или разочарования, даже если клиент отказывается. /
Agent maintains a positive, confident, and respectful tone throughout.
Does not show impatience or disappointment even if the customer declines.
# scripts/outbound_sales.toml
#
# Script definition for outbound sales calls (cold calls, warm leads,
# follow-ups, upsell / cross-sell calls).
#
# Directions: "outbound" only — inbound calls use inbound_support.toml.
#
# Scoring note:
# Objection handling and closing attempt are the highest-weight items
# for a sales call. Both are marked КРИТИЧНО / CRITICAL.
#
# To activate alongside the inbound script:
# [analyzer]
# script_files = [
# "scripts/inbound_support.toml",
# "scripts/outbound_sales.toml",
# ]
script_id = "outbound_sales_v1"
name = "Исходящий звонок — продажи / Outbound sales call"
directions = ["outbound"]
# ── Раздел 1 / Section 1: Opening ─────────────────────────────────────────
[[checklist]]
item = "Представление агента и компании / Agent and company introduction"
description = """
КРИТИЧНО. Агент называет своё имя и компанию в самом начале звонка, до того
как перейти к цели. Пример: «Здравствуйте, меня зовут Иван, я из компании
Ромашка». / CRITICAL. Agent states their name and company at the very start,
before stating the purpose. Example: 'Hi, my name is Ivan calling from
Romashka.'
"""
[[checklist]]
item = "Проверка удобства разговора / Checking if it's a good time"
description = """
Агент спрашивает, удобно ли клиенту говорить прямо сейчас. Пример: «Удобно
ли вам сейчас разговаривать?», 'Is this a good time to talk?' Допускается
пропуск, если клиент сам вступил в разговор активно. /
Agent asks whether it's convenient to speak. May be omitted if the customer
immediately engages enthusiastically.
"""
[[checklist]]
item = "Чёткое обозначение цели звонка / Clear statement of call purpose"
description = """
Агент объясняет, по какому поводу звонит, в первые 30 секунд. Пример:
«Я звоню, чтобы рассказать о нашем новом предложении для постоянных
клиентов», 'I'm calling today because we have a special offer for existing
customers like yourself.' /
Agent states the reason for the call within the first 30 seconds.
"""
# ── Раздел 2 / Section 2: Qualification & needs ───────────────────────────
[[checklist]]
item = "Квалификация клиента / Customer qualification"
description = """
Агент задаёт уточняющие вопросы, чтобы понять, актуально ли предложение для
данного клиента (бюджет, полномочия, потребность, сроки). Пример: «Вы сейчас
пользуетесь подобным решением?», 'Are you currently using any similar
product?' / Agent asks discovery questions to gauge fit (budget, authority,
need, timeline).
"""
[[checklist]]
item = "Выявление потребности / Identifying a pain point or need"
description = """
Агент выявляет конкретную потребность или проблему клиента перед
презентацией. Не переходит к описанию продукта, не услышав о ситуации
клиента. / Agent uncovers a specific need or pain point before pitching.
Does not launch into a product description without first listening.
"""
# ── Раздел 3 / Section 3: Presentation ────────────────────────────────────
[[checklist]]
item = "Презентация под потребность клиента / Tailored value proposition"
description = """
Агент связывает характеристики продукта / услуги с конкретной потребностью,
озвученной клиентом. Не читает универсальный скрипт. Пример: «Учитывая то,
что вы сказали о сроках доставки, нам подойдёт вариант X, потому что…» /
Agent ties product features to the specific need the customer expressed.
Does not recite a generic pitch.
"""
[[checklist]]
item = "Упоминание ключевого УТП или выгоды / Key differentiator or benefit stated"
description = """
Агент явно называет одно или несколько конкурентных преимуществ или выгод.
Пример: «Мы единственные, кто предлагает гарантию возврата в течение 60
дней», 'One thing that sets us apart is the 60-day money-back guarantee.' /
Agent explicitly names at least one differentiator or concrete benefit.
"""
# ── Раздел 4 / Section 4: Objection handling ──────────────────────────────
[[checklist]]
item = "Работа с возражением / Handling at least one objection"
description = """
КРИТИЧНО. Если клиент высказывает возражение (цена, время, необходимость,
конкурент), агент его отрабатывает: выслушивает, уточняет, приводит аргумент
или альтернативу. Не капитулирует при первом возражении. /
CRITICAL. If the customer raises an objection (price, timing, need,
competitor), the agent handles it: acknowledges, clarifies, and responds
with an argument or alternative. Does not give up at the first pushback.
"""
[[checklist]]
item = "Отсутствие давления или спора / No pressure tactics or arguing"
description = """
Агент не спорит с клиентом, не использует давление или манипуляции, не
повторяет одни и те же аргументы более двух раз подряд. /
Agent does not argue with the customer, does not use high-pressure tactics,
and does not repeat the same argument more than twice in a row.
"""
# ── Раздел 5 / Section 5: Closing ─────────────────────────────────────────
[[checklist]]
item = "Попытка закрытия или фиксация следующего шага / Closing attempt or next-step agreement"
description = """
КРИТИЧНО. Агент делает явную попытку закрыть сделку (запрос на покупку,
согласование встречи, подтверждение заявки) или договаривается о конкретном
следующем шаге с датой. Звонок не может завершиться без конкретного итога. /
CRITICAL. Agent makes an explicit close attempt (purchase request, meeting
booking, application confirmation) or agrees on a specific next step with a
date. The call must not end without a concrete outcome.
"""
[[checklist]]
item = "Подтверждение договорённостей / Confirming what was agreed"
description = """
Агент кратко повторяет, что было согласовано: дату, сумму, следующий шаг.
Пример: «Итак, мы договорились, что я пришлю вам коммерческое предложение
до пятницы», 'So we've agreed I'll send you the proposal by Friday.' /
Agent summarises what was agreed: date, amount, or next step.
"""
[[checklist]]
item = "Вежливое завершение звонка / Polite closing"
description = """
Агент благодарит клиента за уделённое время и прощается. Пример: «Спасибо
за ваше время, всего доброго!», 'Thank you for your time — have a great day!'
/ Agent thanks the customer for their time and says a warm goodbye.
"""
# ── Раздел 6 / Section 6: Quality & compliance ────────────────────────────
[[checklist]]
item = "Соблюдение регламента в отношении записи / Compliance with call recording notice"
description = """
Если в компании принято уведомлять клиента о записи разговора, агент
произносит соответствующую фразу в начале звонка. Пропускается, если
уведомление воспроизводится автоматически. /
If company policy requires informing the customer that the call is recorded,
agent states this at the start. May be skipped if an automated recording
notice plays before the agent speaks.
"""
[[checklist]]
item = "Профессиональный тон на протяжении звонка / Professional tone throughout"
description = """
Агент поддерживает позитивный, уверенный и уважительный тон. Не проявляет
нетерпения или разочарования, даже если клиент отказывается. /
Agent maintains a positive, confident, and respectful tone throughout.
Does not show impatience or disappointment even if the customer declines.
"""

View File

@ -1,25 +1,12 @@
from __future__ import annotations
"""analyzer.diarizer — Speaker diarization.
Two strategies:
1. Asterisk (has_rx_tx=True):
Transcribe rx.wav (agent) and tx.wav (customer) independently,
then merge segments sorted by start time.
No ML diarization model is required.
2. Bitrix24 (has_rx_tx=False):
Transcribe the mixed audio.mp3 with Whisper, then run
pyannote/speaker-diarization-3.1 to assign speaker labels.
The first speaker is mapped to "agent" by convention
(overridable via config analyzer.first_speaker_is_agent).
"""
"""analyzer.diarizer - speaker diarization."""
from dataclasses import dataclass
from pathlib import Path
from analyzer.transcriber import BaseTranscriber, RawSegment
from core.config import AnalyzerConfig, get_config
from core.config import get_config
from core.logger import get_logger
log = get_logger(__name__)
@ -28,47 +15,39 @@ SPEAKER_AGENT = "agent"
SPEAKER_CUSTOMER = "customer"
# ---------------------------------------------------------------------------
# Output type
# ---------------------------------------------------------------------------
@dataclass
class DiarizedSegment:
"""A transcribed segment with a confirmed speaker label."""
speaker: str # "agent" | "customer"
speaker: str
start: float
end: float
text: str
# ---------------------------------------------------------------------------
# Strategy 1 — rx/tx alignment (Asterisk)
# ---------------------------------------------------------------------------
def diarize_rx_tx(
rx_path: Path,
tx_path: Path,
transcriber: BaseTranscriber,
direction: str,
language: str | None = None,
) -> list[DiarizedSegment]:
"""Transcribe agent (rx) and customer (tx) channels separately, then merge.
"""Transcribe split channels and map them to speakers using call direction."""
rx.wav → agent segments
tx.wav → customer segments
Merged output is sorted by start time.
"""
log.info("Diarizing via rx/tx channel separation", rx=str(rx_path), tx=str(tx_path))
log.info(
"Diarizing via rx/tx channel separation",
rx=str(rx_path),
tx=str(tx_path),
direction=direction,
)
rx_segments = transcriber.transcribe(rx_path, language=language)
log.info("rx (agent) transcription done", segments=len(rx_segments))
log.info("rx transcription done", segments=len(rx_segments))
tx_segments = transcriber.transcribe(tx_path, language=language)
log.info("tx (customer) transcription done", segments=len(tx_segments))
log.info("tx transcription done", segments=len(tx_segments))
merged = _merge_rx_tx(rx_segments, tx_segments)
merged = _merge_rx_tx(rx_segments, tx_segments, direction)
log.info("rx/tx merge complete", total_segments=len(merged))
return merged
@ -76,49 +55,56 @@ def diarize_rx_tx(
def _merge_rx_tx(
rx_segments: list[RawSegment],
tx_segments: list[RawSegment],
direction: str,
) -> list[DiarizedSegment]:
"""Tag rx as agent, tx as customer, then interleave by start time."""
"""Tag rx/tx using call direction, then interleave by start time."""
if direction == "inbound":
rx_speaker = SPEAKER_AGENT
tx_speaker = SPEAKER_CUSTOMER
elif direction == "outbound":
rx_speaker = SPEAKER_CUSTOMER
tx_speaker = SPEAKER_AGENT
else:
raise ValueError(
f"Call direction must be inbound or outbound for rx/tx diarization, got {direction!r}"
)
tagged: list[DiarizedSegment] = []
for seg in rx_segments:
if seg.text:
tagged.append(DiarizedSegment(
speaker=SPEAKER_AGENT,
start=seg.start,
end=seg.end,
text=seg.text,
))
tagged.append(
DiarizedSegment(
speaker=rx_speaker,
start=seg.start,
end=seg.end,
text=seg.text,
)
)
for seg in tx_segments:
if seg.text:
tagged.append(DiarizedSegment(
speaker=SPEAKER_CUSTOMER,
start=seg.start,
end=seg.end,
text=seg.text,
))
tagged.append(
DiarizedSegment(
speaker=tx_speaker,
start=seg.start,
end=seg.end,
text=seg.text,
)
)
return sorted(tagged, key=lambda s: s.start)
# ---------------------------------------------------------------------------
# Strategy 2 — pyannote fallback (Bitrix24 mixed audio)
# ---------------------------------------------------------------------------
def diarize_mixed(
audio_path: Path,
transcriber: BaseTranscriber,
first_speaker_is_agent: bool = True,
language: str | None = None,
) -> list[DiarizedSegment]:
"""Transcribe mixed audio then run pyannote for speaker segmentation.
"""Transcribe mixed audio then run pyannote for speaker segmentation."""
Speaker mapping:
The speaker who appears first in the diarization timeline is mapped
to "agent" when first_speaker_is_agent=True (default), otherwise
to "customer".
"""
log.info("Diarizing via pyannote (mixed audio)", path=str(audio_path))
raw_segments = transcriber.transcribe(audio_path, language=language)
@ -128,13 +114,16 @@ def diarize_mixed(
return []
diarization = _run_pyannote(audio_path)
merged = _align_transcript_with_diarization(raw_segments, diarization, first_speaker_is_agent)
merged = _align_transcript_with_diarization(
raw_segments, diarization, first_speaker_is_agent
)
log.info("pyannote diarization complete", total_segments=len(merged))
return merged
def _run_pyannote(audio_path: Path) -> list[tuple[float, float, str]]:
"""Run pyannote diarization; return list of (start, end, speaker_label)."""
try:
from pyannote.audio import Pipeline
except ImportError as exc:
@ -144,6 +133,7 @@ def _run_pyannote(audio_path: Path) -> list[tuple[float, float, str]]:
) from exc
import os
from typing import Any, cast
hf_token = os.environ.get("HF_TOKEN")
if not hf_token:
@ -153,9 +143,9 @@ def _run_pyannote(audio_path: Path) -> list[tuple[float, float, str]]:
)
log.info("Loading pyannote diarization pipeline")
pipeline = Pipeline.from_pretrained(
pipeline = cast(Any, Pipeline).from_pretrained(
"pyannote/speaker-diarization-3.1",
use_auth_token=hf_token,
token=hf_token,
)
diarization = pipeline(str(audio_path))
@ -172,37 +162,35 @@ def _align_transcript_with_diarization(
diarization_turns: list[tuple[float, float, str]],
first_speaker_is_agent: bool,
) -> list[DiarizedSegment]:
"""Assign speaker labels to transcript segments by overlap with diarization turns.
"""Assign speaker labels to transcript segments by overlap with diarization turns."""
For each transcript segment, find the diarization turn with the greatest
time overlap and use that speaker label.
"""
if not diarization_turns:
log.warning("No diarization turns found; marking all segments as agent")
return [
DiarizedSegment(speaker=SPEAKER_AGENT, start=s.start, end=s.end, text=s.text)
DiarizedSegment(
speaker=SPEAKER_AGENT, start=s.start, end=s.end, text=s.text
)
for s in raw_segments
if s.text
]
# Build speaker → role mapping from the first occurrence
first_speaker = min(diarization_turns, key=lambda t: t[0])[2]
role_map: dict[str, str] = {}
def _role(label: str) -> str:
if label not in role_map:
if not role_map:
# First speaker encountered
role_map[label] = SPEAKER_AGENT if first_speaker_is_agent else SPEAKER_CUSTOMER
role_map[label] = (
SPEAKER_AGENT if first_speaker_is_agent else SPEAKER_CUSTOMER
)
else:
# All subsequent speakers → other role
existing_roles = set(role_map.values())
role_map[label] = (
SPEAKER_CUSTOMER if SPEAKER_AGENT in existing_roles else SPEAKER_AGENT
SPEAKER_CUSTOMER
if SPEAKER_AGENT in existing_roles
else SPEAKER_AGENT
)
return role_map[label]
# Pre-compute roles for all known speakers
for _, _, spk in diarization_turns:
_role(spk)
@ -211,12 +199,14 @@ def _align_transcript_with_diarization(
if not seg.text:
continue
best_speaker = _best_speaker_for_segment(seg, diarization_turns)
result.append(DiarizedSegment(
speaker=_role(best_speaker) if best_speaker else SPEAKER_AGENT,
start=seg.start,
end=seg.end,
text=seg.text,
))
result.append(
DiarizedSegment(
speaker=_role(best_speaker) if best_speaker else SPEAKER_AGENT,
start=seg.start,
end=seg.end,
text=seg.text,
)
)
return result
@ -226,6 +216,7 @@ def _best_speaker_for_segment(
turns: list[tuple[float, float, str]],
) -> str | None:
"""Return the speaker label with the greatest overlap with *seg*."""
best_label: str | None = None
best_overlap = 0.0
@ -240,18 +231,15 @@ def _best_speaker_for_segment(
return best_label
# ---------------------------------------------------------------------------
# Dispatcher
# ---------------------------------------------------------------------------
def diarize(
spool_dir: Path,
has_rx_tx: bool,
transcriber: BaseTranscriber,
direction: str,
language: str | None = None,
) -> list[DiarizedSegment]:
"""Choose the correct diarization strategy based on *has_rx_tx*."""
cfg = get_config()
if has_rx_tx:
@ -259,12 +247,13 @@ def diarize(
rx_path=spool_dir / "rx.wav",
tx_path=spool_dir / "tx.wav",
transcriber=transcriber,
direction=direction,
language=language,
)
else:
return diarize_mixed(
audio_path=spool_dir / "audio.mp3",
transcriber=transcriber,
first_speaker_is_agent=cfg.analyzer.first_speaker_is_agent,
language=language,
)
return diarize_mixed(
audio_path=spool_dir / "audio.mp3",
transcriber=transcriber,
first_speaker_is_agent=cfg.analyzer.first_speaker_is_agent,
language=language,
)

View File

@ -1,158 +1,175 @@
from __future__ import annotations
"""analyzer.emotion — Per-segment emotion classification.
Two backends:
"transformers" — j-hartmann/emotion-english-distilroberta-base (local, fast)
"llm" — structured JSON prompt via core.llm (any configured provider)
Output is always an emotion label + confidence score appended to each segment dict.
"""
from dataclasses import dataclass
from typing import Literal
from core.config import AnalyzerConfig, get_config
from core.logger import get_logger
log = get_logger(__name__)
EmotionLabel = Literal[
"neutral", "positive", "negative", "angry", "fearful", "surprised", "sad"
]
# Mapping from model-specific labels to our canonical set
_LABEL_MAP: dict[str, EmotionLabel] = {
# j-hartmann model labels
"neutral": "neutral",
"joy": "positive",
"disgust": "negative",
"anger": "angry",
"fear": "fearful",
"surprise": "surprised",
"sadness": "sad",
# fallback synonyms
"happy": "positive",
"sad": "sad",
}
VALID_EMOTIONS: set[EmotionLabel] = {
"neutral", "positive", "negative", "angry", "fearful", "surprised", "sad"
}
@dataclass
class EmotionResult:
label: EmotionLabel
score: float # 0.0–1.0 confidence
# ---------------------------------------------------------------------------
# Transformers backend
# ---------------------------------------------------------------------------
class TransformersEmotionClassifier:
"""Runs emotion classification locally using a HuggingFace pipeline."""
def __init__(self, model_name: str) -> None:
from transformers import pipeline as hf_pipeline
log.info("Loading emotion model", model=model_name)
self._pipe = hf_pipeline(
"text-classification",
model=model_name,
top_k=1,
truncation=True,
max_length=512,
)
def classify_batch(self, texts: list[str]) -> list[EmotionResult]:
if not texts:
return []
# transformers pipeline accepts a list; returns list[list[dict]]
results = self._pipe(texts)
out: list[EmotionResult] = []
for item in results:
top = item[0] if isinstance(item, list) else item
raw_label = top["label"].lower()
label: EmotionLabel = _LABEL_MAP.get(raw_label, "neutral")
out.append(EmotionResult(label=label, score=round(float(top["score"]), 4)))
return out
def classify(self, text: str) -> EmotionResult:
return self.classify_batch([text])[0]
# ---------------------------------------------------------------------------
# LLM backend
# ---------------------------------------------------------------------------
class LLMEmotionClassifier:
"""Classifies emotion via LLM — slower but language-agnostic."""
_SYSTEM = (
"You are an emotion classifier. "
"Given a short spoken text segment, respond ONLY with a JSON object "
'with keys "label" and "score". '
f'"label" must be one of: {", ".join(sorted(VALID_EMOTIONS))}. '
'"score" is a float 0.0–1.0 representing confidence. '
"No explanation, no markdown, just the JSON object."
)
def classify(self, text: str) -> EmotionResult:
from analyzer.llm import call_llm_json
prompt = f'Classify the emotion in this text:\n\n"{text}"'
data = call_llm_json(self._SYSTEM, prompt, schema_hint={"label": str, "score": float})
label_raw = str(data.get("label", "neutral")).lower()
label: EmotionLabel = label_raw if label_raw in VALID_EMOTIONS else "neutral" # type: ignore[assignment]
score = float(data.get("score", 0.5))
return EmotionResult(label=label, score=round(score, 4))
def classify_batch(self, texts: list[str]) -> list[EmotionResult]:
# LLM backend classifies one at a time; could be batched in future
return [self.classify(t) for t in texts]
# ---------------------------------------------------------------------------
# Factory + public API
# ---------------------------------------------------------------------------
def make_emotion_classifier():
cfg = get_config()
match cfg.analyzer.emotion_backend:
case "transformers":
return TransformersEmotionClassifier(cfg.analyzer.emotion_model)
case "llm":
return LLMEmotionClassifier()
case unknown:
raise ValueError(f"Unknown emotion_backend: {unknown!r}")
def enrich_with_emotions(
segments: list[dict],
classifier,
) -> list[dict]:
"""Add ``emotion`` and ``emotion_score`` fields to each segment dict in-place.
Args:
segments: List of segment dicts (already have speaker/start/end/text).
classifier: An instance of TransformersEmotionClassifier or LLMEmotionClassifier.
Returns:
The same list with emotion fields added.
"""
texts = [s.get("text", "") for s in segments]
results = classifier.classify_batch(texts)
for seg, result in zip(segments, results):
from __future__ import annotations
"""analyzer.emotion — Per-segment emotion classification.
Two backends:
"transformers" — j-hartmann/emotion-english-distilroberta-base (local, fast)
"llm" — structured JSON prompt via core.llm (any configured provider)
Output is always an emotion label + confidence score appended to each segment dict.
"""
from dataclasses import dataclass
from typing import Any, Literal, cast
from core.config import get_config
from core.logger import get_logger
log = get_logger(__name__)
EmotionLabel = Literal[
"neutral", "positive", "negative", "angry", "fearful", "surprised", "sad"
]
# Mapping from model-specific labels to our canonical set
_LABEL_MAP: dict[str, EmotionLabel] = {
# j-hartmann model labels
"neutral": "neutral",
"joy": "positive",
"disgust": "negative",
"anger": "angry",
"fear": "fearful",
"surprise": "surprised",
"sadness": "sad",
# fallback synonyms
"happy": "positive",
"sad": "sad",
}
VALID_EMOTIONS: set[EmotionLabel] = {
"neutral",
"positive",
"negative",
"angry",
"fearful",
"surprised",
"sad",
}
@dataclass
class EmotionResult:
label: EmotionLabel
score: float # 0.0–1.0 confidence
# ---------------------------------------------------------------------------
# Transformers backend
# ---------------------------------------------------------------------------
class TransformersEmotionClassifier:
"""Runs emotion classification locally using a HuggingFace pipeline."""
def __init__(self, model_name: str) -> None:
from transformers import pipeline as hf_pipeline
log.info("Loading emotion model", model=model_name)
self._pipe = hf_pipeline(
"text-classification",
model=model_name,
top_k=1,
truncation=True,
max_length=512,
)
def classify_batch(self, texts: list[str]) -> list[EmotionResult]:
if not texts:
return []
# transformers pipeline accepts a list; returns list[list[dict]]
results: list[Any] = self._pipe(texts)
out: list[EmotionResult] = []
for item in results:
if isinstance(item, list):
top_dict = cast(dict[str, Any], item[0])
else:
top_dict = cast(dict[str, Any], item)
raw_label = str(top_dict.get("label", "neutral")).lower()
label = _LABEL_MAP.get(raw_label)
if label is None:
label = "neutral"
out.append(
EmotionResult(label=label, score=round(float(top_dict["score"]), 4))
)
return out
def classify(self, text: str) -> EmotionResult:
return self.classify_batch([text])[0]
# ---------------------------------------------------------------------------
# LLM backend
# ---------------------------------------------------------------------------
class LLMEmotionClassifier:
"""Classifies emotion via LLM — slower but language-agnostic."""
_SYSTEM = (
"You are an emotion classifier. "
"Given a short spoken text segment, respond ONLY with a JSON object "
'with keys "label" and "score". '
f'"label" must be one of: {", ".join(sorted(VALID_EMOTIONS))}. '
'"score" is a float 0.0–1.0 representing confidence. '
"No explanation, no markdown, just the JSON object."
)
def classify(self, text: str) -> EmotionResult:
from analyzer.llm import call_llm_json
prompt = f'Classify the emotion in this text:\n\n"{text}"'
data = call_llm_json(
self._SYSTEM, prompt, schema_hint={"label": str, "score": float}
)
label_raw = str(data.get("label", "neutral")).lower()
label = (
cast(EmotionLabel, label_raw) if label_raw in VALID_EMOTIONS else "neutral"
)
score = float(data.get("score", 0.5))
return EmotionResult(label=label, score=round(score, 4))
def classify_batch(self, texts: list[str]) -> list[EmotionResult]:
# LLM backend classifies one at a time; could be batched in future
return [self.classify(t) for t in texts]
# ---------------------------------------------------------------------------
# Factory + public API
# ---------------------------------------------------------------------------
def make_emotion_classifier():
cfg = get_config()
match cfg.analyzer.emotion_backend:
case "transformers":
return TransformersEmotionClassifier(cfg.analyzer.emotion_model)
case "llm":
return LLMEmotionClassifier()
case unknown:
raise ValueError(f"Unknown emotion_backend: {unknown!r}")
def enrich_with_emotions(
segments: list[dict],
classifier,
) -> list[dict]:
"""Add ``emotion`` and ``emotion_score`` fields to each segment dict in-place.
Args:
segments: List of segment dicts (already have speaker/start/end/text).
classifier: An instance of TransformersEmotionClassifier or LLMEmotionClassifier.
Returns:
The same list with emotion fields added.
"""
texts = [s.get("text", "") for s in segments]
results = classifier.classify_batch(texts)
for seg, result in zip(segments, results, strict=False):
seg["emotion"] = result.label
seg["emotion_score"] = result.score
log.info("Emotion enrichment done", segments=len(segments))
return segments
log.info("Emotion enrichment done", segments=len(segments))
return segments

View File

@ -1,17 +1,12 @@
from __future__ import annotations
"""analyzer.llm — Unified LLM caller used by script_check and emotion (llm backend).
All calls request JSON output. Responses are validated and retried up to
llm_retry_attempts times before raising.
"""
"""analyzer.llm - analyzer-owned QA LLM caller."""
import json
from typing import Any
from core.config import get_config
from core.logger import get_logger
from core.retry import retry_sync
log = get_logger(__name__)
@ -25,21 +20,10 @@ def call_llm_json(
user_prompt: str,
schema_hint: dict[str, type] | None = None,
) -> dict[str, Any]:
"""Call the configured LLM and parse the response as JSON.
"""Call the configured QA provider and parse the response as JSON."""
Args:
system_prompt: System / instruction message.
user_prompt: User turn content.
schema_hint: Optional dict of expected keys → types for light validation.
Returns:
Parsed JSON dict.
Raises:
LLMError: If valid JSON cannot be obtained after retries.
"""
cfg = get_config()
attempts = cfg.llm.llm_retry_attempts
attempts = cfg.analyzer.retry_attempts
for attempt in range(1, attempts + 1):
try:
@ -51,61 +35,59 @@ def call_llm_json(
except (LLMError, ValueError, KeyError) as exc:
log.warning("LLM JSON parse failed", attempt=attempt, error=str(exc))
if attempt == attempts:
raise LLMError(f"LLM failed to return valid JSON after {attempts} attempts") from exc
raise LLMError(
f"LLM failed to return valid JSON after {attempts} attempts"
) from exc
raise LLMError("Unreachable")
# ---------------------------------------------------------------------------
# Backend dispatch
# ---------------------------------------------------------------------------
def _call_backend(system_prompt: str, user_prompt: str) -> str:
cfg = get_config()
match cfg.llm.backend:
case "cloud":
match cfg.llm.provider:
case "anthropic":
return _call_anthropic(system_prompt, user_prompt)
case "openai":
return _call_openai(system_prompt, user_prompt)
case p:
raise ValueError(f"Unknown cloud provider: {p!r}")
case "local":
match cfg.analyzer.provider:
case "openai":
return _call_openai(system_prompt, user_prompt)
case "groq":
return _call_groq(system_prompt, user_prompt)
case "ollama":
return _call_ollama(system_prompt, user_prompt)
case b:
raise ValueError(f"Unknown LLM backend: {b!r}")
def _call_anthropic(system_prompt: str, user_prompt: str) -> str:
import anthropic
cfg = get_config()
api_key = cfg.llm.api_key or None # None → ANTHROPIC_API_KEY env var
client = anthropic.Anthropic(api_key=api_key)
message = client.messages.create(
model=cfg.llm.model,
max_tokens=cfg.llm.max_tokens,
temperature=cfg.llm.temperature,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}],
)
return message.content[0].text
case "local_whisper":
raise ValueError("provider=local_whisper does not support QA LLM calls")
case provider:
raise ValueError(f"Unknown analyzer provider: {provider!r}")
def _call_openai(system_prompt: str, user_prompt: str) -> str:
import openai
cfg = get_config()
api_key = cfg.llm.api_key or None
api_key = cfg.analyzer.api_key or None
client = openai.OpenAI(api_key=api_key)
response = client.chat.completions.create(
model=cfg.llm.model,
max_tokens=cfg.llm.max_tokens,
temperature=cfg.llm.temperature,
model=cfg.analyzer.qa_model,
max_tokens=cfg.analyzer.qa_max_tokens,
temperature=cfg.analyzer.qa_temperature,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
response_format={"type": "json_object"},
)
return response.choices[0].message.content or ""
def _call_groq(system_prompt: str, user_prompt: str) -> str:
import groq
cfg = get_config()
api_key = cfg.analyzer.api_key or None
client = groq.Groq(api_key=api_key)
response = client.chat.completions.create(
model=cfg.analyzer.qa_model,
max_tokens=cfg.analyzer.qa_max_tokens,
temperature=cfg.analyzer.qa_temperature,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
@ -119,9 +101,9 @@ def _call_ollama(system_prompt: str, user_prompt: str) -> str:
import httpx
cfg = get_config()
url = cfg.llm.ollama_url.rstrip("/") + "/api/chat"
url = cfg.analyzer.ollama_url.rstrip("/") + "/api/chat"
payload = {
"model": cfg.llm.ollama_model,
"model": cfg.analyzer.qa_model,
"stream": False,
"messages": [
{"role": "system", "content": system_prompt},
@ -135,18 +117,10 @@ def _call_ollama(system_prompt: str, user_prompt: str) -> str:
return resp.json()["message"]["content"]
# ---------------------------------------------------------------------------
# JSON parsing + light schema validation
# ---------------------------------------------------------------------------
def _parse_json(raw: str) -> dict[str, Any]:
"""Strip markdown fences if present, then parse JSON."""
text = raw.strip()
# Strip ```json ... ``` or ``` ... ``` wrappers
if text.startswith("```"):
lines = text.splitlines()
# Remove first and last fence lines
inner = lines[1:] if lines[0].startswith("```") else lines
inner = inner[:-1] if inner and inner[-1].strip() == "```" else inner
text = "\n".join(inner).strip()

View File

@ -1,22 +1,17 @@
from __future__ import annotations
"""analyzer.main — Process 2 entry point.
Long-running systemd service. Polls the DB for calls with status=spooled,
runs the full analysis pipeline (transcribe → diarize → emotion → script check),
writes artifacts, and advances the call status.
"""
"""analyzer.main - Process 2 entry point."""
import json
import os
import time
from dataclasses import asdict
from datetime import datetime, timezone
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from sqlmodel import select
from collector.spooler import update_meta_status
from collector.spooler import read_meta, update_meta_status
from core.config import load_config
from core.db import get_session, init_db
from core.logger import configure_logging, get_logger
@ -25,13 +20,9 @@ from core.models import AnalysisArtifact, CallRecord, CallStatus
log = get_logger(__name__)
# ---------------------------------------------------------------------------
# Artifact writer
# ---------------------------------------------------------------------------
def _write_json_artifact(path: Path, data: object) -> None:
"""Write *data* to *path* atomically."""
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
os.rename(tmp, path)
@ -54,48 +45,112 @@ def _register_artifact(
session.add(artifact)
# ---------------------------------------------------------------------------
# Per-call pipeline
# ---------------------------------------------------------------------------
def _load_call_meta(record: CallRecord) -> dict[str, Any]:
try:
meta = read_meta(record.spool_path)
except Exception:
meta = {}
meta.setdefault("uniqueid", record.uniqueid)
meta.setdefault("source", record.source)
meta.setdefault("direction", record.direction or "unknown")
meta.setdefault("has_rx_tx", record.has_rx_tx)
return meta
def _dialog_line(turn: dict[str, Any]) -> str:
start_s = int(turn.get("start", 0))
minutes, seconds = divmod(start_s, 60)
timestamp = f"{minutes:02d}:{seconds:02d}"
speaker = str(turn.get("speaker", "unknown")).capitalize()
emotion = str(turn.get("emotion", "")).strip()
emotion_tag = f" [{emotion}]" if emotion and emotion != "neutral" else ""
text = str(turn.get("text", "")).strip()
return f"[{timestamp}] {speaker}{emotion_tag}: {text}"
def _build_transcript_artifact(
meta: dict[str, Any],
turns: list[dict[str, Any]],
diarization_strategy: str,
) -> dict[str, Any]:
dialog_text = "\n".join(_dialog_line(turn) for turn in turns)
return {
"uniqueid": meta.get("uniqueid"),
"source": meta.get("source"),
"direction": meta.get("direction", "unknown"),
"has_rx_tx": bool(meta.get("has_rx_tx", False)),
"diarization_strategy": diarization_strategy,
"dialog_text": dialog_text,
"turns": turns,
"stats": {
"turn_count": len(turns),
"agent_turns": sum(1 for turn in turns if turn.get("speaker") == "agent"),
"customer_turns": sum(
1 for turn in turns if turn.get("speaker") == "customer"
),
},
}
def process_call(record: CallRecord, transcriber, emotion_classifier) -> None:
"""Run the full analysis pipeline for one CallRecord.
"""Run the full analysis pipeline for one CallRecord."""
Status transitions: spooled → processing → analyzed | failed
"""
uid = record.uniqueid
spool_dir = record.spool_path
call_start = time.monotonic()
log.info("Processing call START", uniqueid=uid, source=record.source, has_rx_tx=record.has_rx_tx)
meta = _load_call_meta(record)
has_rx_tx = bool(meta.get("has_rx_tx", record.has_rx_tx))
direction = str(meta.get("direction", record.direction or "unknown"))
if has_rx_tx and direction not in {"inbound", "outbound"}:
raise RuntimeError(
f"Split-channel call {uid!r} has unusable direction in meta.json: {direction!r}"
)
call_start = time.monotonic()
log.info(
"Processing call START",
uniqueid=uid,
source=meta.get("source", record.source),
has_rx_tx=has_rx_tx,
direction=direction,
)
if record.id is None:
raise RuntimeError(f"CallRecord {uid!r} has no primary key; cannot process")
record_id = record.id
# --- Mark as processing ---
with get_session() as session:
rec = session.get(CallRecord, record.id)
rec = session.get(CallRecord, record_id)
rec.status = CallStatus.PROCESSING
update_meta_status(spool_dir, CallStatus.PROCESSING)
try:
# 1. Diarization (includes transcription)
from analyzer.diarizer import diarize
from analyzer.emotion import enrich_with_emotions
from analyzer.script_check import analyse_call, analysis_to_dict
step_t = time.monotonic()
log.info("Step 1/4: transcription + diarization START", uniqueid=uid)
diarized = diarize(
spool_dir=spool_dir,
has_rx_tx=record.has_rx_tx,
has_rx_tx=has_rx_tx,
transcriber=transcriber,
direction=direction,
)
log.info(
"Step 1/4: transcription + diarization DONE",
uniqueid=uid,
segments=len(diarized),
elapsed_s=round(time.monotonic() - step_t, 2),
)
log.info("Step 1/4: transcription + diarization DONE",
uniqueid=uid, segments=len(diarized), elapsed_s=round(time.monotonic() - step_t, 2))
if not diarized:
log.warning("No segments produced; marking failed", uniqueid=uid)
_mark_failed(record, "Transcription produced no segments")
return
# Convert to plain dicts for further processing + JSON serialisation
segments: list[dict] = [
turns: list[dict[str, Any]] = [
{
"speaker": seg.speaker,
"start": seg.start,
@ -105,60 +160,76 @@ def process_call(record: CallRecord, transcriber, emotion_classifier) -> None:
for seg in diarized
]
# 2. Emotion enrichment
from analyzer.emotion import enrich_with_emotions
step_t = time.monotonic()
log.info("Step 2/4: emotion classification START", uniqueid=uid, segments=len(segments))
segments = enrich_with_emotions(segments, emotion_classifier)
log.info("Step 2/4: emotion classification DONE",
uniqueid=uid, elapsed_s=round(time.monotonic() - step_t, 2))
log.info(
"Step 2/4: emotion classification START",
uniqueid=uid,
segments=len(turns),
)
turns = enrich_with_emotions(turns, emotion_classifier)
log.info(
"Step 2/4: emotion classification DONE",
uniqueid=uid,
elapsed_s=round(time.monotonic() - step_t, 2),
)
# 3. Write transcript.json
transcript_path = spool_dir / "transcript.json"
_write_json_artifact(transcript_path, segments)
log.info("Step 3/4: transcript.json written", uniqueid=uid, segments=len(segments))
# 4. Script compliance check (optional — no-op if no scripts configured)
from analyzer.script_check import analyse_call, analysis_to_dict
transcript_artifact = _build_transcript_artifact(
meta=meta,
turns=turns,
diarization_strategy="rx_tx" if has_rx_tx else "pyannote",
)
_write_json_artifact(transcript_path, transcript_artifact)
log.info("Step 3/4: transcript.json written", uniqueid=uid, segments=len(turns))
step_t = time.monotonic()
log.info("Step 4/4: script compliance check START", uniqueid=uid)
analysis_result = analyse_call(
transcript_segments=segments,
direction=record.direction or "unknown",
transcript_segments=turns,
direction=direction,
uniqueid=uid,
)
if analysis_result is not None:
analysis_path = spool_dir / "analysis.json"
_write_json_artifact(analysis_path, analysis_to_dict(analysis_result))
log.info("Step 4/4: script compliance DONE",
uniqueid=uid, score=analysis_result.score,
elapsed_s=round(time.monotonic() - step_t, 2))
log.info(
"Step 4/4: script compliance DONE",
uniqueid=uid,
score=analysis_result.score,
elapsed_s=round(time.monotonic() - step_t, 2),
)
else:
analysis_path = None
log.info("Step 4/4: script compliance SKIPPED (no scripts configured)", uniqueid=uid)
log.info(
"Step 4/4: script compliance SKIPPED (no scripts configured)",
uniqueid=uid,
)
# 5. Persist artifacts + advance status
with get_session() as session:
rec = session.get(CallRecord, record.id)
rec = session.get(CallRecord, record_id)
_register_artifact(session, record.id, uid, "transcript", transcript_path)
_register_artifact(session, record_id, uid, "transcript", transcript_path)
if analysis_path and analysis_path.exists():
_register_artifact(session, record.id, uid, "analysis", analysis_path)
_register_artifact(session, record_id, uid, "analysis", analysis_path)
rec.status = CallStatus.ANALYZED
rec.analyzed_at = datetime.now(timezone.utc)
rec.analyzed_at = datetime.now(UTC)
update_meta_status(spool_dir, CallStatus.ANALYZED)
log.info("Call analysis COMPLETE",
uniqueid=uid, total_elapsed_s=round(time.monotonic() - call_start, 2))
log.info(
"Call analysis COMPLETE",
uniqueid=uid,
total_elapsed_s=round(time.monotonic() - call_start, 2),
)
except Exception as exc:
log.exception("Unhandled error during call analysis",
uniqueid=uid, error=str(exc),
elapsed_s=round(time.monotonic() - call_start, 2))
log.exception(
"Unhandled error during call analysis",
uniqueid=uid,
error=str(exc),
elapsed_s=round(time.monotonic() - call_start, 2),
)
_mark_failed(record, str(exc))
@ -166,22 +237,21 @@ def _mark_failed(record: CallRecord, error: str) -> None:
with get_session() as session:
rec = session.get(CallRecord, record.id)
rec.failure_count = (rec.failure_count or 0) + 1
rec.last_error = error[:2000] # truncate for DB column
rec.last_error = error[:2000]
if rec.failure_count >= 3:
rec.status = CallStatus.DEAD_LETTER
log.error("Call moved to dead_letter", uniqueid=record.uniqueid, failures=rec.failure_count)
log.error(
"Call moved to dead_letter",
uniqueid=record.uniqueid,
failures=rec.failure_count,
)
else:
rec.status = CallStatus.FAILED
update_meta_status(record.spool_path, rec.status, error=error)
# ---------------------------------------------------------------------------
# Main loop
# ---------------------------------------------------------------------------
def main() -> None:
cfg = load_config()
configure_logging(level="INFO", json=True)
@ -189,14 +259,15 @@ def main() -> None:
log.info("Analyzer service starting", poll_interval_s=cfg.schedule.poll_interval_s)
# Initialise heavy models once, reuse across calls
from analyzer.transcriber import make_transcriber
from analyzer.emotion import make_emotion_classifier
from analyzer.transcriber import make_transcriber
step_t = time.monotonic()
log.info("Loading transcription model...")
transcriber = make_transcriber()
log.info("Transcription model loaded", elapsed_s=round(time.monotonic() - step_t, 2))
log.info(
"Transcription model loaded", elapsed_s=round(time.monotonic() - step_t, 2)
)
step_t = time.monotonic()
log.info("Loading emotion model...")
@ -204,10 +275,10 @@ def main() -> None:
log.info("Emotion model loaded", elapsed_s=round(time.monotonic() - step_t, 2))
from core.daemon import GracefulExit
stop = GracefulExit()
while not stop.requested:
# Fetch a batch of spooled (or previously failed) calls to process
with get_session() as session:
pending = session.exec(
select(CallRecord)
@ -217,7 +288,9 @@ def main() -> None:
).all()
if not pending:
log.debug("No pending calls; sleeping", seconds=cfg.schedule.poll_interval_s)
log.debug(
"No pending calls; sleeping", seconds=cfg.schedule.poll_interval_s
)
stop.sleep(cfg.schedule.poll_interval_s)
continue
@ -229,7 +302,11 @@ def main() -> None:
try:
process_call(record, transcriber, emotion_classifier)
except Exception as exc:
log.exception("Fatal error in process_call", uniqueid=record.uniqueid, error=str(exc))
log.exception(
"Fatal error in process_call",
uniqueid=record.uniqueid,
error=str(exc),
)
log.info("Analyzer shutting down cleanly")

View File

@ -1,259 +1,283 @@
from __future__ import annotations
"""analyzer.script_check — Script compliance checking and call ranking.
Script definitions live in TOML files referenced by config.analyzer.script_files.
Each script file defines a call type and a list of checklist items the agent
is expected to cover.
The LLM is given the full transcript text and the checklist, and returns
a structured JSON analysis artifact.
"""
import tomllib
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from analyzer.llm import LLMError, call_llm_json
from core.config import get_config
from core.logger import get_logger
log = get_logger(__name__)
# ---------------------------------------------------------------------------
# Script definition (loaded from TOML)
# ---------------------------------------------------------------------------
@dataclass
class ChecklistItem:
item: str
description: str = ""
@dataclass
class ScriptDefinition:
script_id: str
name: str
# call directions this script applies to: ["inbound"], ["outbound"], or ["inbound","outbound"]
directions: list[str] = field(default_factory=lambda: ["inbound", "outbound"])
checklist: list[ChecklistItem] = field(default_factory=list)
def load_script_definitions() -> list[ScriptDefinition]:
"""Load all script TOML files listed in config."""
cfg = get_config()
definitions: list[ScriptDefinition] = []
for script_path in cfg.analyzer.script_files:
path = Path(script_path)
if not path.is_absolute():
# resolve relative to config dir
env_config = Path(__import__("os").environ.get(
"VOICE_PIPELINE_CONFIG", "/etc/voice-pipeline/config.toml"
))
path = env_config.parent / path
if not path.exists():
log.warning("Script file not found; skipping", path=str(path))
continue
try:
with path.open("rb") as fh:
raw = tomllib.load(fh)
definition = ScriptDefinition(
script_id=raw["script_id"],
name=raw.get("name", raw["script_id"]),
directions=raw.get("directions", ["inbound", "outbound"]),
checklist=[
ChecklistItem(item=c["item"], description=c.get("description", ""))
for c in raw.get("checklist", [])
],
)
definitions.append(definition)
log.info("Loaded script definition", script_id=definition.script_id, items=len(definition.checklist))
except (KeyError, ValueError, OSError) as exc:
log.error("Failed to load script file", path=str(path), error=str(exc))
return definitions
def select_script(definitions: list[ScriptDefinition], direction: str) -> ScriptDefinition | None:
"""Return the first script definition that matches the call direction."""
for defn in definitions:
if direction in defn.directions:
return defn
return None
# ---------------------------------------------------------------------------
# Analysis result
# ---------------------------------------------------------------------------
@dataclass
class ChecklistResult:
item: str
passed: bool
evidence: str | None # verbatim quote or paraphrase from transcript
@dataclass
class AnalysisResult:
script_id: str
score: int # 0–100
summary: str
checklist: list[ChecklistResult]
# ---------------------------------------------------------------------------
# LLM prompt
# ---------------------------------------------------------------------------
_SYSTEM = """\
You are a quality assurance analyst evaluating a customer service call.
You will receive:
1. A diarized transcript of the call (JSON array of segments with speaker, text).
2. A compliance checklist — items the agent is expected to address.
Respond ONLY with a JSON object (no markdown, no explanation) with this exact structure:
{
"score": <integer 0-100>,
"summary": "<one or two sentence overall assessment>",
"checklist": [
{
"item": "<checklist item text>",
"passed": <true|false>,
"evidence": "<brief quote or null>"
}
]
}
Scoring guide:
100 = all checklist items passed perfectly
0 = no checklist items addressed
Deduct proportionally per missed item; weigh critical items more heavily.
"""
def _build_user_prompt(
transcript_segments: list[dict],
script: ScriptDefinition,
call_meta: dict[str, Any],
) -> str:
import json
transcript_text = json.dumps(
[{"speaker": s["speaker"], "text": s["text"]} for s in transcript_segments],
ensure_ascii=False,
indent=2,
)
checklist_text = "\n".join(
f"- {item.item}" + (f": {item.description}" if item.description else "")
for item in script.checklist
)
return (
f"Call direction: {call_meta.get('direction', 'unknown')}\n"
f"Script: {script.name} ({script.script_id})\n\n"
f"Checklist items:\n{checklist_text}\n\n"
f"Transcript:\n{transcript_text}"
)
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def analyse_call(
transcript_segments: list[dict],
direction: str,
uniqueid: str,
) -> AnalysisResult | None:
"""Run script compliance analysis on *transcript_segments*.
Returns None if no applicable script definition is found.
Raises LLMError if the LLM fails after retries.
"""
definitions = load_script_definitions()
if not definitions:
log.info("No script definitions configured; skipping compliance check", uniqueid=uniqueid)
return None
script = select_script(definitions, direction)
if script is None:
log.info(
"No script matches call direction; skipping",
uniqueid=uniqueid,
direction=direction,
)
return None
log.info("Running script compliance check", uniqueid=uniqueid, script_id=script.script_id)
user_prompt = _build_user_prompt(
transcript_segments=transcript_segments,
script=script,
call_meta={"direction": direction},
)
try:
data = call_llm_json(
system_prompt=_SYSTEM,
user_prompt=user_prompt,
schema_hint={"score": int, "summary": str, "checklist": list},
)
except LLMError as exc:
log.error("Script check LLM failed", uniqueid=uniqueid, error=str(exc))
raise
checklist_results = [
ChecklistResult(
item=c.get("item", ""),
passed=bool(c.get("passed", False)),
evidence=c.get("evidence"),
)
for c in data.get("checklist", [])
]
result = AnalysisResult(
script_id=script.script_id,
score=max(0, min(100, int(data.get("score", 0)))),
summary=str(data.get("summary", "")),
checklist=checklist_results,
)
log.info(
"Script compliance done",
uniqueid=uniqueid,
script_id=script.script_id,
score=result.score,
passed=sum(1 for c in result.checklist if c.passed),
total=len(result.checklist),
)
return result
from __future__ import annotations
"""analyzer.script_check — Script compliance checking and call ranking.
Script definitions live in TOML files referenced by config.analyzer.script_files.
Each script file defines a call type and a list of checklist items the agent
is expected to cover.
The LLM is given the full transcript text and the checklist, and returns
a structured JSON analysis artifact.
"""
import tomllib
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from analyzer.llm import LLMError, call_llm_json
from core.config import get_config
from core.logger import get_logger
log = get_logger(__name__)
# ---------------------------------------------------------------------------
# Script definition (loaded from TOML)
# ---------------------------------------------------------------------------
@dataclass
class ChecklistItem:
item: str
description: str = ""
@dataclass
class ScriptDefinition:
script_id: str
name: str
# call directions this script applies to: ["inbound"], ["outbound"], or ["inbound","outbound"]
directions: list[str] = field(default_factory=lambda: ["inbound", "outbound"])
checklist: list[ChecklistItem] = field(default_factory=list)
def load_script_definitions() -> list[ScriptDefinition]:
"""Load all script TOML files listed in config."""
cfg = get_config()
definitions: list[ScriptDefinition] = []
for script_path in cfg.analyzer.script_files:
path = Path(script_path)
if not path.is_absolute():
# resolve relative to config dir
env_config = Path(
__import__("os").environ.get(
"VOICE_PIPELINE_CONFIG", "/etc/voice-pipeline/config.toml"
)
)
path = env_config.parent / path
if not path.exists():
log.warning("Script file not found; skipping", path=str(path))
continue
try:
with path.open("rb") as fh:
raw = tomllib.load(fh)
definition = ScriptDefinition(
script_id=raw["script_id"],
name=raw.get("name", raw["script_id"]),
directions=raw.get("directions", ["inbound", "outbound"]),
checklist=[
ChecklistItem(item=c["item"], description=c.get("description", ""))
for c in raw.get("checklist", [])
],
)
definitions.append(definition)
log.info(
"Loaded script definition",
script_id=definition.script_id,
items=len(definition.checklist),
)
except (KeyError, ValueError, OSError) as exc:
log.error("Failed to load script file", path=str(path), error=str(exc))
return definitions
def select_script(
definitions: list[ScriptDefinition], direction: str
) -> ScriptDefinition | None:
"""Return the first script definition that matches the call direction."""
for defn in definitions:
if direction in defn.directions:
return defn
return None
# ---------------------------------------------------------------------------
# Analysis result
# ---------------------------------------------------------------------------
@dataclass
class ChecklistResult:
item: str
passed: bool
evidence: str | None # verbatim quote or paraphrase from transcript
@dataclass
class AnalysisResult:
script_id: str
score: int # 0–100
summary: str
checklist: list[ChecklistResult]
# ---------------------------------------------------------------------------
# LLM prompt
# ---------------------------------------------------------------------------
_SYSTEM = """\
You are a quality assurance analyst evaluating a customer service call.
You will receive:
1. A diarized transcript of the call (JSON array of segments with speaker, text).
2. A compliance checklist — items the agent is expected to address.
Respond ONLY with a JSON object (no markdown, no explanation) with this exact structure:
{
"score": <integer 0-100>,
"summary": "<one or two sentence overall assessment>",
"checklist": [
{
"item": "<checklist item text>",
"passed": <true|false>,
"evidence": "<brief quote or null>"
}
]
}
Scoring guide:
100 = all checklist items passed perfectly
0 = no checklist items addressed
Deduct proportionally per missed item; weigh critical items more heavily.
"""
def _build_user_prompt(
transcript_segments: list[dict],
script: ScriptDefinition,
call_meta: dict[str, Any],
) -> str:
import json
transcript_text = json.dumps(
[{"speaker": s["speaker"], "text": s["text"]} for s in transcript_segments],
ensure_ascii=False,
indent=2,
)
checklist_text = "\n".join(
f"- {item.item}" + (f": {item.description}" if item.description else "")
for item in script.checklist
)
return (
f"Call direction: {call_meta.get('direction', 'unknown')}\n"
f"Script: {script.name} ({script.script_id})\n\n"
f"Checklist items:\n{checklist_text}\n\n"
f"Transcript:\n{transcript_text}"
)
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def analyse_call(
transcript_segments: list[dict],
direction: str,
uniqueid: str,
) -> AnalysisResult | None:
"""Run script compliance analysis on *transcript_segments*.
Returns None if no applicable script definition is found.
Raises LLMError if the LLM fails after retries.
"""
definitions = load_script_definitions()
if not definitions:
log.info(
"No script definitions configured; skipping compliance check",
uniqueid=uniqueid,
)
return None
script = select_script(definitions, direction)
if script is None:
log.info(
"No script matches call direction; skipping",
uniqueid=uniqueid,
direction=direction,
)
return None
log.info(
"Running script compliance check", uniqueid=uniqueid, script_id=script.script_id
)
user_prompt = _build_user_prompt(
transcript_segments=transcript_segments,
script=script,
call_meta={"direction": direction},
)
try:
data = call_llm_json(
system_prompt=_SYSTEM,
user_prompt=user_prompt,
schema_hint={"score": int, "summary": str, "checklist": list},
)
except LLMError as exc:
log.error("Script check LLM failed", uniqueid=uniqueid, error=str(exc))
raise
checklist_results = [
ChecklistResult(
item=c.get("item", ""),
passed=bool(c.get("passed", False)),
evidence=c.get("evidence"),
)
for c in data.get("checklist", [])
]
result = AnalysisResult(
script_id=script.script_id,
score=max(0, min(100, int(data.get("score", 0)))),
summary=str(data.get("summary", "")),
checklist=checklist_results,
)
log.info(
"Script compliance done",
uniqueid=uniqueid,
script_id=script.script_id,
score=result.score,
passed=sum(1 for c in result.checklist if c.passed),
total=len(result.checklist),
)
return result
def analysis_to_dict(result: AnalysisResult) -> dict[str, Any]:
"""Serialise AnalysisResult to a plain dict (for JSON artifact)."""
passed_count = sum(1 for c in result.checklist if c.passed)
total_count = len(result.checklist)
summary = result.summary.strip()
bitrix_summary = (
f"Score {result.score}/100. Passed {passed_count}/{total_count}. {summary}"
if summary
else f"Score {result.score}/100. Passed {passed_count}/{total_count}."
)
return {
"script_id": result.script_id,
"score": result.score,
"summary": result.summary,
"bitrix_summary": bitrix_summary,
"passed_count": passed_count,
"total_count": total_count,
"checklist": [
{
"item": c.item,
"passed": c.passed,
"evidence": c.evidence,
}
for c in result.checklist
],
}
"passed": c.passed,
"evidence": c.evidence,
}
for c in result.checklist
],
}

View File

@ -1,32 +1,23 @@
from __future__ import annotations
"""analyzer.transcriber — Whisper transcription backends.
Each backend returns a list of RawSegment objects with start/end/text.
The diarizer consumes these and adds speaker labels.
"""
"""analyzer.transcriber - transcription backends."""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from core.config import AnalyzerConfig, LLMConfig, get_config
from core.config import AnalyzerConfig, get_config
from core.logger import get_logger
from core.retry import retry_sync
log = get_logger(__name__)
# ---------------------------------------------------------------------------
# Shared data type
# ---------------------------------------------------------------------------
@dataclass
class RawSegment:
"""One transcription segment as returned by Whisper (no speaker label yet)."""
"""One transcription segment as returned by the transcription provider."""
start: float # seconds from audio start
start: float
end: float
text: str
@ -34,36 +25,29 @@ class RawSegment:
self.text = self.text.strip()
# ---------------------------------------------------------------------------
# Abstract base
# ---------------------------------------------------------------------------
class BaseTranscriber(ABC):
@abstractmethod
def transcribe(self, audio_path: Path, language: str | None = None) -> list[RawSegment]:
def transcribe(
self, audio_path: Path, language: str | None = None
) -> list[RawSegment]:
"""Transcribe *audio_path* and return time-aligned segments."""
# ---------------------------------------------------------------------------
# OpenAI Whisper (cloud)
# ---------------------------------------------------------------------------
class OpenAITranscriber(BaseTranscriber):
"""Calls the OpenAI Whisper API (whisper-1 or compatible model)."""
"""Calls the OpenAI audio transcription API."""
def __init__(self, llm_cfg: LLMConfig, analyzer_cfg: AnalyzerConfig) -> None:
def __init__(self, analyzer_cfg: AnalyzerConfig) -> None:
import openai
api_key = llm_cfg.api_key or None # None → falls back to OPENAI_API_KEY env var
api_key = analyzer_cfg.api_key or None
self._client = openai.OpenAI(api_key=api_key)
self._model = analyzer_cfg.whisper_model
self._retry_attempts = llm_cfg.llm_retry_attempts
self._model = analyzer_cfg.transcription_model
@retry_sync(attempts=3, backoff_s=2.0)
def transcribe(self, audio_path: Path, language: str | None = None) -> list[RawSegment]:
log.info("Transcribing via OpenAI Whisper", path=str(audio_path), model=self._model)
def transcribe(
self, audio_path: Path, language: str | None = None
) -> list[RawSegment]:
log.info("Transcribing via OpenAI", path=str(audio_path), model=self._model)
with audio_path.open("rb") as fh:
kwargs: dict = {
@ -85,30 +69,70 @@ class OpenAITranscriber(BaseTranscriber):
return segments
# ---------------------------------------------------------------------------
# faster-whisper (local)
# ---------------------------------------------------------------------------
class GroqTranscriber(BaseTranscriber):
"""Calls the Groq audio transcription API."""
def __init__(self, analyzer_cfg: AnalyzerConfig) -> None:
import groq
api_key = analyzer_cfg.api_key or None
self._client = groq.Groq(api_key=api_key)
self._model = analyzer_cfg.transcription_model
@retry_sync(attempts=3, backoff_s=2.0)
def transcribe(
self, audio_path: Path, language: str | None = None
) -> list[RawSegment]:
log.info("Transcribing via Groq", path=str(audio_path), model=self._model)
with audio_path.open("rb") as fh:
kwargs: dict = {
"model": self._model,
"file": fh,
"response_format": "verbose_json",
"timestamp_granularities": ["segment"],
}
if language:
kwargs["language"] = language
response = self._client.audio.transcriptions.create(**kwargs)
segments = [
RawSegment(start=seg.start, end=seg.end, text=seg.text)
for seg in (response.segments or [])
]
log.info("Transcription complete", path=str(audio_path), segments=len(segments))
return segments
class FasterWhisperTranscriber(BaseTranscriber):
"""Uses faster-whisper running locally (CPU or CUDA)."""
class LocalWhisperTranscriber(BaseTranscriber):
"""Uses a locally installed Whisper model via faster-whisper."""
def __init__(self, analyzer_cfg: AnalyzerConfig) -> None:
from faster_whisper import WhisperModel
if analyzer_cfg.local_whisper_model_dir is None:
raise ValueError(
"local_whisper_model_dir is required for provider=local_whisper"
)
log.info(
"Loading faster-whisper model",
model=analyzer_cfg.faster_whisper_model,
device=analyzer_cfg.faster_whisper_device,
"Loading local Whisper model",
model=str(analyzer_cfg.local_whisper_model_dir),
device=analyzer_cfg.local_whisper_device,
)
self._model = WhisperModel(
analyzer_cfg.faster_whisper_model,
device=analyzer_cfg.faster_whisper_device,
compute_type="float16" if analyzer_cfg.faster_whisper_device == "cuda" else "int8",
str(analyzer_cfg.local_whisper_model_dir),
device=analyzer_cfg.local_whisper_device,
compute_type=(
"float16" if analyzer_cfg.local_whisper_device == "cuda" else "int8"
),
)
def transcribe(self, audio_path: Path, language: str | None = None) -> list[RawSegment]:
log.info("Transcribing via faster-whisper", path=str(audio_path))
def transcribe(
self, audio_path: Path, language: str | None = None
) -> list[RawSegment]:
log.info("Transcribing via local Whisper", path=str(audio_path))
kwargs: dict = {"beam_size": 5}
if language:
@ -121,7 +145,7 @@ class FasterWhisperTranscriber(BaseTranscriber):
for seg in fw_segments
]
log.info(
"faster-whisper transcription complete",
"Local Whisper transcription complete",
path=str(audio_path),
language=info.language,
segments=len(segments),
@ -129,18 +153,18 @@ class FasterWhisperTranscriber(BaseTranscriber):
return segments
# ---------------------------------------------------------------------------
# Factory
# ---------------------------------------------------------------------------
def make_transcriber() -> BaseTranscriber:
"""Instantiate the correct transcriber from config."""
cfg = get_config()
match cfg.analyzer.whisper_backend:
match cfg.analyzer.provider:
case "openai":
return OpenAITranscriber(cfg.llm, cfg.analyzer)
case "faster-whisper":
return FasterWhisperTranscriber(cfg.analyzer)
return OpenAITranscriber(cfg.analyzer)
case "groq":
return GroqTranscriber(cfg.analyzer)
case "local_whisper":
return LocalWhisperTranscriber(cfg.analyzer)
case unknown:
raise ValueError(f"Unknown whisper_backend: {unknown!r}")
raise ValueError(
f"Analyzer provider does not support transcription: {unknown!r}"
)

View File

@ -4,11 +4,10 @@ import re
import stat as stat_mod
import time
from collections import defaultdict
from contextlib import contextmanager
from contextlib import suppress
from dataclasses import dataclass
from datetime import datetime, timezone
from datetime import date, datetime
from pathlib import Path
from typing import Generator
import httpx
import paramiko
@ -29,9 +28,9 @@ class WavSet:
"""A complete, stable set of 3 WAV files for one call."""
uniqueid: str
mixed: str # remote relative path
rx: str # remote relative path (agent side)
tx: str # remote relative path (customer side)
mixed: str # remote relative path
rx: str # remote relative path (agent side)
tx: str # remote relative path (customer side)
direction: str = "unknown" # "inbound" | "outbound" | "unknown"
@ -72,7 +71,7 @@ def group_wav_files(filenames: list[str], pattern: str) -> list[WavSet]:
m = compiled.match(Path(name).name)
if not m:
continue
uid = m.group("uid")
uid = m.group("uid")
suffix = (m.group("suffix") or "").lower()
if suffix == "-rx":
@ -108,9 +107,10 @@ def group_wav_files(filenames: list[str], pattern: str) -> list[WavSet]:
def _load_pkey(path: Path) -> paramiko.PKey:
"""Load a private key of any supported type (Ed25519 → ECDSA → RSA)."""
key_classes: list = [paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.RSAKey]
if hasattr(paramiko, "DSSKey"):
key_classes.append(paramiko.DSSKey)
key_classes: list[type] = [paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.RSAKey]
dss_key = getattr(paramiko, "DSSKey", None)
if dss_key is not None:
key_classes.append(dss_key)
for key_class in key_classes:
try:
@ -138,8 +138,7 @@ def _date_paths_for_lookback(lookback_days: int) -> list[str]:
today = datetime.now().date()
return [
(today - timedelta(days=d)).strftime("%Y/%m/%d")
for d in range(lookback_days)
(today - timedelta(days=d)).strftime("%Y/%m/%d") for d in range(lookback_days)
]
@ -165,7 +164,7 @@ def _sftp_list_dir_flat(
for entry in entries:
if not stat_mod.S_ISDIR(entry.st_mode or 0):
full_path = f"{remote_path}/{entry.filename}"
rel = full_path[len(base):].lstrip("/")
rel = full_path[len(base) :].lstrip("/")
result.append(rel)
return result
@ -199,9 +198,11 @@ def _sftp_list_recursive(
try:
result.extend(_sftp_list_recursive(sftp, full_path, _root))
except OSError as exc:
log.warning("Skipping inaccessible subdir", path=full_path, error=str(exc))
log.warning(
"Skipping inaccessible subdir", path=full_path, error=str(exc)
)
else:
rel = full_path[len(_root):].lstrip("/")
rel = full_path[len(_root) :].lstrip("/")
result.append(rel)
return result
@ -259,16 +260,12 @@ class SFTPTransport:
def close(self) -> None:
if self._sftp:
try:
with suppress(Exception):
self._sftp.close()
except Exception:
pass
self._sftp = None
if self._transport:
try:
with suppress(Exception):
self._transport.close()
except Exception:
pass
self._transport = None
@property
@ -296,13 +293,17 @@ class SFTPTransport:
if not date_paths:
# lookback_days=0 → scan everything
log.info("Listing all files (lookback_days=0)", remote_path=self._cfg.remote_path)
log.info(
"Listing all files (lookback_days=0)", remote_path=self._cfg.remote_path
)
return _sftp_list_recursive(self.sftp, self._cfg.remote_path)
log.info("Listing files for date range",
days=self._cfg.lookback_days,
from_date=date_paths[-1],
to_date=date_paths[0])
log.info(
"Listing files for date range",
days=self._cfg.lookback_days,
from_date=date_paths[-1],
to_date=date_paths[0],
)
result: list[str] = []
base = self._cfg.remote_path
@ -313,9 +314,28 @@ class SFTPTransport:
if files:
log.debug("Date dir listed", path=date_path, files=len(files))
log.info("Total files found", count=len(result), date_dirs_scanned=len(date_paths))
log.info(
"Total files found", count=len(result), date_dirs_scanned=len(date_paths)
)
return result
def list_files_for_date(self, day: date) -> list[str]:
"""Return relative files only from YYYY/MM/DD directory for the given date."""
base = self._cfg.remote_path
day_path = day.strftime("%Y/%m/%d")
return _sftp_list_dir_flat(self.sftp, f"{base}/{day_path}", base)
def find_wav_set_for_external_call_id(
self, day: date, external_call_id: str
) -> WavSet | None:
"""Locate one WAV triplet by external/origin call id within the specified date directory."""
files = self.list_files_for_date(day)
matched = [name for name in files if external_call_id in Path(name).name]
if not matched:
return None
grouped = group_wav_files(matched, self._cfg.filename_pattern)
return grouped[0] if grouped else None
def get_file_size(self, relative_path: str) -> int:
full = f"{self._cfg.remote_path}/{relative_path}"
attr = self.sftp.stat(full)
@ -336,27 +356,35 @@ class SFTPTransport:
after = [self.get_file_size(n) for n in names]
stable = before == after and all(s > 0 for s in after)
if not stable:
log.warning("WAV set not yet stable", uniqueid=wav_set.uniqueid,
before=before, after=after)
log.warning(
"WAV set not yet stable",
uniqueid=wav_set.uniqueid,
before=before,
after=after,
)
return stable
def download(self, relative_path: str, local_path: Path) -> None:
"""Download a single remote file using the persistent session."""
remote = f"{self._cfg.remote_path}/{relative_path}"
self.sftp.get(remote, str(local_path))
log.info("Downloaded", remote_file=Path(relative_path).name, local=local_path.name)
log.info(
"Downloaded", remote_file=Path(relative_path).name, local=local_path.name
)
def download_set(self, wav_set: WavSet, dest_dir: Path) -> None:
"""Download all 3 WAVs into dest_dir as mixed.wav / rx.wav / tx.wav."""
dest_dir.mkdir(parents=True, exist_ok=True)
log.info("Downloading WAV set",
uniqueid=wav_set.uniqueid,
mixed=Path(wav_set.mixed).name,
rx=Path(wav_set.rx).name,
tx=Path(wav_set.tx).name)
log.info(
"Downloading WAV set",
uniqueid=wav_set.uniqueid,
mixed=Path(wav_set.mixed).name,
rx=Path(wav_set.rx).name,
tx=Path(wav_set.tx).name,
)
self.download(wav_set.mixed, dest_dir / "mixed.wav")
self.download(wav_set.rx, dest_dir / "rx.wav")
self.download(wav_set.tx, dest_dir / "tx.wav")
self.download(wav_set.rx, dest_dir / "rx.wav")
self.download(wav_set.tx, dest_dir / "tx.wav")
log.info("WAV set downloaded", uniqueid=wav_set.uniqueid)
@ -384,13 +412,19 @@ class HTTPTransport:
return f"{self._cfg.base_url.rstrip('/')}/{filename}"
def list_files(self) -> list[str]:
@retry_sync(attempts=self._cfg.retry_attempts, backoff_s=self._cfg.retry_backoff_s,
exceptions=(httpx.HTTPError,))
@retry_sync(
attempts=self._cfg.retry_attempts,
backoff_s=self._cfg.retry_backoff_s,
exceptions=(httpx.HTTPError,),
)
def _do() -> list[str]:
with httpx.Client(timeout=30.0) as client:
resp = client.get(self._cfg.base_url.rstrip("/") + "/", headers=self._headers)
resp = client.get(
self._cfg.base_url.rstrip("/") + "/", headers=self._headers
)
resp.raise_for_status()
return resp.json().get("files", [])
return _do()
def get_file_size(self, filename: str) -> int:
@ -414,28 +448,38 @@ class HTTPTransport:
def download(self, remote_filename: str, local_path: Path) -> None:
url = self._url(remote_filename)
@retry_sync(attempts=self._cfg.retry_attempts, backoff_s=self._cfg.retry_backoff_s,
exceptions=(httpx.HTTPError,))
@retry_sync(
attempts=self._cfg.retry_attempts,
backoff_s=self._cfg.retry_backoff_s,
exceptions=(httpx.HTTPError,),
)
def _do() -> None:
with httpx.Client(timeout=httpx.Timeout(120.0, connect=10.0)) as client:
with client.stream("GET", url, headers=self._headers) as resp:
resp.raise_for_status()
with local_path.open("wb") as fh:
for chunk in resp.iter_bytes(chunk_size=65536):
fh.write(chunk)
with (
httpx.Client(timeout=httpx.Timeout(120.0, connect=10.0)) as client,
client.stream("GET", url, headers=self._headers) as resp,
):
resp.raise_for_status()
with local_path.open("wb") as fh:
for chunk in resp.iter_bytes(chunk_size=65536):
fh.write(chunk)
_do()
log.info("Downloaded", remote_file=Path(remote_filename).name, local=local_path.name)
log.info(
"Downloaded", remote_file=Path(remote_filename).name, local=local_path.name
)
def download_set(self, wav_set: WavSet, dest_dir: Path) -> None:
dest_dir.mkdir(parents=True, exist_ok=True)
log.info("Downloading WAV set",
uniqueid=wav_set.uniqueid,
mixed=Path(wav_set.mixed).name,
rx=Path(wav_set.rx).name,
tx=Path(wav_set.tx).name)
log.info(
"Downloading WAV set",
uniqueid=wav_set.uniqueid,
mixed=Path(wav_set.mixed).name,
rx=Path(wav_set.rx).name,
tx=Path(wav_set.tx).name,
)
self.download(wav_set.mixed, dest_dir / "mixed.wav")
self.download(wav_set.rx, dest_dir / "rx.wav")
self.download(wav_set.tx, dest_dir / "tx.wav")
self.download(wav_set.rx, dest_dir / "rx.wav")
self.download(wav_set.tx, dest_dir / "tx.wav")
log.info("WAV set downloaded", uniqueid=wav_set.uniqueid)

View File

@ -1,286 +1,464 @@
from __future__ import annotations
"""collector.bitrix_enrichment — Enrich call metadata via Bitrix24 API.
Two enrichment paths:
1. **Asterisk calls** — batch-fetch voximplant.statistic.get for a time window,
build a local dict keyed by EXTERNAL_CALL_ID (= Asterisk UNIQUEID),
then look up each call locally. This avoids per-call API requests and
works around the fact that Bitrix24 does NOT support filtering
voximplant.statistic.get by EXTERNAL_CALL_ID.
2. **"My calls"** — activity already fetched via crm.activity.list; resolve
the owning CRM entity (lead/deal/contact/company) and the user.
"""
from datetime import datetime, timedelta
from typing import Any
from core.bitrix_client import Bitrix24Client, Bitrix24Error
from core.logger import get_logger
log = get_logger(__name__)
_CRM_ENTITY_METHOD = {
"LEAD": "crm.lead.get",
"DEAL": "crm.deal.get",
"CONTACT": "crm.contact.get",
"COMPANY": "crm.company.get",
}
_OWNER_TYPE_MAP = {
"1": "LEAD",
"2": "DEAL",
"3": "CONTACT",
"4": "COMPANY",
}
# ═══════════════════════════════════════════════════════════════════════════
# 1. Asterisk enrichment — batch voximplant stats
# ═══════════════════════════════════════════════════════════════════════════
def fetch_voximplant_stats(
client: Bitrix24Client,
date_from: str,
date_to: str,
) -> dict[str, dict]:
"""Fetch ALL voximplant call statistics for a date range with pagination.
Bitrix24 does NOT support filtering by EXTERNAL_CALL_ID, so we must
paginate through the full result set and build a local lookup dict.
Args:
client: Bitrix24Client instance.
date_from: Start date as "YYYY-MM-DD" (inclusive).
date_to: End date as "YYYY-MM-DD" (inclusive, +1 day added internally).
Returns:
Dict mapping EXTERNAL_CALL_ID → voximplant record.
Only records with a non-empty EXTERNAL_CALL_ID are included.
"""
# Add 1 day to date_to to make it inclusive
try:
dt_to = datetime.strptime(date_to, "%Y-%m-%d") + timedelta(days=1)
date_to_filter = dt_to.strftime("%Y-%m-%dT00:00:00")
except ValueError:
date_to_filter = f"{date_to}T23:59:59"
date_from_filter = f"{date_from}T00:00:00"
log.info("Fetching voximplant statistics",
date_from=date_from_filter, date_to=date_to_filter)
lookup: dict[str, dict] = {}
start = 0
total_fetched = 0
while True:
try:
result = client.call("voximplant.statistic.get", {
"FILTER": {
">=CALL_START_DATE": date_from_filter,
"<CALL_START_DATE": date_to_filter,
},
"SORT": "CALL_START_DATE",
"ORDER": "ASC",
"start": start,
})
except Bitrix24Error as exc:
log.error("voximplant.statistic.get failed", error=str(exc), start=start)
break
if not result or not isinstance(result, list):
break
for rec in result:
ext_id = rec.get("EXTERNAL_CALL_ID", "")
if ext_id:
lookup[ext_id] = rec
total_fetched += len(result)
log.debug("Voximplant page fetched", page_size=len(result), total=total_fetched)
if len(result) < 50:
break # last page (Bitrix24 default page size is 50)
start += 50
log.info("Voximplant stats fetched",
total_records=total_fetched,
with_external_id=len(lookup))
return lookup
def enrich_asterisk_call(
client: Bitrix24Client,
uniqueid: str,
voxi_stats: dict[str, dict],
) -> dict[str, Any]:
"""Enrich a single Asterisk call using pre-fetched voximplant statistics.
Args:
client: Bitrix24Client for follow-up entity/user queries.
uniqueid: Asterisk UNIQUEID, e.g. "1782360309.131865".
voxi_stats: Pre-fetched lookup from fetch_voximplant_stats().
Returns:
Dict with: voximplant_call, crm_activity, crm_entity, crm_entity_type,
crm_company, crm_user.
"""
result: dict[str, Any] = {
"voximplant_call": None,
"crm_activity": None,
"crm_entity": None,
"crm_entity_type": None,
"crm_company": None,
"crm_user": None,
}
# Step 1: Find in pre-fetched voximplant stats
voxi = voxi_stats.get(uniqueid)
if voxi is None:
log.debug("No voximplant record for UNIQUEID", uniqueid=uniqueid)
return result
result["voximplant_call"] = voxi
log.info("Voximplant record matched",
uniqueid=uniqueid,
call_id=voxi.get("CALL_ID"),
crm_activity_id=voxi.get("CRM_ACTIVITY_ID"),
portal_user_id=voxi.get("PORTAL_USER_ID"))
# Step 2: Get CRM activity by CRM_ACTIVITY_ID
activity_id = str(voxi.get("CRM_ACTIVITY_ID", "") or "")
if activity_id:
activity = _get_activity(client, activity_id)
if activity:
result["crm_activity"] = activity
# Step 3: Resolve CRM entity
crm_type = voxi.get("CRM_ENTITY_TYPE")
crm_id = str(voxi.get("CRM_ENTITY_ID", "") or "")
_resolve_entity_chain(client, crm_type, crm_id, result)
# Step 4: Resolve user
user_id = str(voxi.get("PORTAL_USER_ID", "") or "")
if user_id:
result["crm_user"] = _get_user(client, user_id)
return result
# ═══════════════════════════════════════════════════════════════════════════
# 2. "My calls" enrichment
# ═══════════════════════════════════════════════════════════════════════════
def enrich_mycall_activity(
client: Bitrix24Client,
activity: dict,
) -> dict[str, Any]:
"""Enrich a 'my calls' CRM activity with entity and user data.
Args:
client: Bitrix24Client instance.
activity: Raw activity dict from crm.activity.list.
Returns:
Dict with: crm_activity, crm_entity, crm_entity_type,
crm_company, crm_user.
"""
result: dict[str, Any] = {
"crm_activity": activity,
"crm_entity": None,
"crm_entity_type": None,
"crm_company": None,
"crm_user": None,
}
# Resolve CRM entity by OWNER_TYPE_ID / OWNER_ID
owner_type_id = str(activity.get("OWNER_TYPE_ID", ""))
owner_id = str(activity.get("OWNER_ID", "") or "")
entity_type = _OWNER_TYPE_MAP.get(owner_type_id)
_resolve_entity_chain(client, entity_type, owner_id, result)
# Resolve user
user_id = str(
activity.get("RESPONSIBLE_ID")
or activity.get("AUTHOR_ID")
or ""
)
if user_id:
result["crm_user"] = _get_user(client, user_id)
return result
# ═══════════════════════════════════════════════════════════════════════════
# Shared helpers
# ═══════════════════════════════════════════════════════════════════════════
def _resolve_entity_chain(
client: Bitrix24Client,
entity_type: str | None,
entity_id: str,
result: dict,
) -> None:
"""Resolve CRM entity and its company (if applicable) into *result*."""
if not entity_type or not entity_id or entity_type not in _CRM_ENTITY_METHOD:
return
entity = _get_crm_entity(client, entity_type, entity_id)
if not entity:
return
result["crm_entity"] = entity
result["crm_entity_type"] = entity_type
# If entity has COMPANY_ID, resolve the company too
company_id = str(entity.get("COMPANY_ID", "") or "")
if company_id and entity_type != "COMPANY":
company = _get_crm_entity(client, "COMPANY", company_id)
if company:
result["crm_company"] = company
log.debug("Company resolved",
company_id=company_id, title=company.get("TITLE"))
def _get_activity(client: Bitrix24Client, activity_id: str) -> dict | None:
try:
result = client.call("crm.activity.get", {"ID": activity_id})
return result if isinstance(result, dict) else None
except Bitrix24Error as exc:
log.warning("crm.activity.get failed",
activity_id=activity_id, error=str(exc))
return None
def _get_crm_entity(
client: Bitrix24Client,
entity_type: str,
entity_id: str,
) -> dict | None:
method = _CRM_ENTITY_METHOD.get(entity_type)
if not method:
return None
try:
result = client.call(method, {"ID": entity_id})
return result if isinstance(result, dict) else None
except Bitrix24Error as exc:
log.warning("CRM entity fetch failed",
method=method, entity_id=entity_id, error=str(exc))
return None
def _get_user(client: Bitrix24Client, user_id: str) -> dict | None:
try:
result = client.call("user.get", {"ID": user_id})
if isinstance(result, list) and result:
return result[0]
return None
except Bitrix24Error as exc:
log.warning("user.get failed", user_id=user_id, error=str(exc))
return None
from __future__ import annotations
"""collector.bitrix_enrichment — Enrich call metadata via Bitrix24 API.
Two enrichment paths:
1. **Asterisk calls** — batch-fetch voximplant.statistic.get for a time window,
build a local dict keyed by EXTERNAL_CALL_ID (= Asterisk UNIQUEID),
then look up each call locally. This avoids per-call API requests and
works around the fact that Bitrix24 does NOT support filtering
voximplant.statistic.get by EXTERNAL_CALL_ID.
2. **"My calls"** — activity already fetched via crm.activity.list; resolve
the owning CRM entity (lead/deal/contact/company) and the user.
"""
<<<<<<< HEAD
from datetime import UTC, datetime, timedelta
=======
from datetime import datetime, timedelta
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
from typing import Any
from core.bitrix_client import Bitrix24Client, Bitrix24Error
from core.logger import get_logger
log = get_logger(__name__)
_CRM_ENTITY_METHOD = {
"LEAD": "crm.lead.get",
"DEAL": "crm.deal.get",
"CONTACT": "crm.contact.get",
"COMPANY": "crm.company.get",
}
_OWNER_TYPE_MAP = {
"1": "LEAD",
"2": "DEAL",
"3": "CONTACT",
"4": "COMPANY",
}
<<<<<<< HEAD
# CRM entity → REST method for get
_ENTITY_GET_METHOD = {
"LEAD": "crm.lead.get",
"DEAL": "crm.deal.get",
"CONTACT": "crm.contact.get",
"COMPANY": "crm.company.get",
}
_ACTIVITY_SELECT = [
"ID",
"SUBJECT",
"CREATED",
"START_TIME",
"END_TIME",
"COMPLETED",
"OWNER_TYPE_ID",
"OWNER_ID",
"PROVIDER_ID",
"PROVIDER_TYPE_ID",
"DIRECTION",
"RESPONSIBLE_ID",
"AUTHOR_ID",
"ORIGIN_ID",
]
=======
# ═══════════════════════════════════════════════════════════════════════════
# 1. Asterisk enrichment — batch voximplant stats
# ═══════════════════════════════════════════════════════════════════════════
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
def fetch_voximplant_stats(
client: Bitrix24Client,
date_from: str,
date_to: str,
) -> dict[str, dict]:
"""Fetch ALL voximplant call statistics for a date range with pagination.
Bitrix24 does NOT support filtering by EXTERNAL_CALL_ID, so we must
paginate through the full result set and build a local lookup dict.
Args:
client: Bitrix24Client instance.
date_from: Start date as "YYYY-MM-DD" (inclusive).
date_to: End date as "YYYY-MM-DD" (inclusive, +1 day added internally).
Returns:
Dict mapping EXTERNAL_CALL_ID → voximplant record.
Only records with a non-empty EXTERNAL_CALL_ID are included.
"""
# Add 1 day to date_to to make it inclusive
try:
dt_to = datetime.strptime(date_to, "%Y-%m-%d") + timedelta(days=1)
date_to_filter = dt_to.strftime("%Y-%m-%dT00:00:00")
except ValueError:
date_to_filter = f"{date_to}T23:59:59"
date_from_filter = f"{date_from}T00:00:00"
log.info("Fetching voximplant statistics",
date_from=date_from_filter, date_to=date_to_filter)
lookup: dict[str, dict] = {}
start = 0
total_fetched = 0
while True:
try:
result = client.call("voximplant.statistic.get", {
"FILTER": {
">=CALL_START_DATE": date_from_filter,
"<CALL_START_DATE": date_to_filter,
},
"SORT": "CALL_START_DATE",
"ORDER": "ASC",
"start": start,
})
except Bitrix24Error as exc:
log.error("voximplant.statistic.get failed", error=str(exc), start=start)
break
if not result or not isinstance(result, list):
break
for rec in result:
ext_id = rec.get("EXTERNAL_CALL_ID", "")
if ext_id:
lookup[ext_id] = rec
total_fetched += len(result)
log.debug("Voximplant page fetched", page_size=len(result), total=total_fetched)
if len(result) < 50:
break # last page (Bitrix24 default page size is 50)
start += 50
log.info("Voximplant stats fetched",
total_records=total_fetched,
with_external_id=len(lookup))
return lookup
def enrich_asterisk_call(
client: Bitrix24Client,
uniqueid: str,
voxi_stats: dict[str, dict],
) -> dict[str, Any]:
"""Enrich a single Asterisk call using pre-fetched voximplant statistics.
Args:
client: Bitrix24Client for follow-up entity/user queries.
uniqueid: Asterisk UNIQUEID, e.g. "1782360309.131865".
voxi_stats: Pre-fetched lookup from fetch_voximplant_stats().
Returns:
Dict with: voximplant_call, crm_activity, crm_entity, crm_entity_type,
crm_company, crm_user.
"""
result: dict[str, Any] = {
"voximplant_call": None,
"crm_activity": None,
"crm_entity": None,
"crm_entity_type": None,
"crm_company": None,
"crm_user": None,
}
<<<<<<< HEAD
# Build time window from call datetime (±1 day)
since, until = _time_window(call_datetime)
# Step 1: Find the activity
activity = _find_activity(client, origin_id, since, until, phone)
if activity is None:
log.info(
"No Bitrix24 activity found",
uniqueid=uniqueid,
origin_id=origin_id,
phone=phone,
since=since,
until=until,
)
=======
# Step 1: Find in pre-fetched voximplant stats
voxi = voxi_stats.get(uniqueid)
if voxi is None:
log.debug("No voximplant record for UNIQUEID", uniqueid=uniqueid)
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
return result
result["voximplant_call"] = voxi
log.info("Voximplant record matched",
uniqueid=uniqueid,
call_id=voxi.get("CALL_ID"),
crm_activity_id=voxi.get("CRM_ACTIVITY_ID"),
portal_user_id=voxi.get("PORTAL_USER_ID"))
# Step 2: Get CRM activity by CRM_ACTIVITY_ID
activity_id = str(voxi.get("CRM_ACTIVITY_ID", "") or "")
if activity_id:
activity = _get_activity(client, activity_id)
if activity:
result["crm_activity"] = activity
# Step 3: Resolve CRM entity
crm_type = voxi.get("CRM_ENTITY_TYPE")
crm_id = str(voxi.get("CRM_ENTITY_ID", "") or "")
_resolve_entity_chain(client, crm_type, crm_id, result)
<<<<<<< HEAD
# Step 3: If entity has a COMPANY_ID, resolve the company
company_id = str(entity.get("COMPANY_ID", "") or "")
if company_id and entity_type != "COMPANY":
company = _get_crm_entity(client, "COMPANY", company_id)
if company:
result["crm_company"] = company
log.debug(
"Company resolved",
company_id=company_id,
title=company.get("TITLE"),
)
# Step 4: Resolve the responsible user
user_id = (
activity.get("RESPONSIBLE_ID")
or activity.get("AUTHOR_ID")
or activity.get("PORTAL_USER_ID")
)
if user_id:
user = _get_user(client, str(user_id))
if user:
result["crm_user"] = user
log.debug(
"User resolved",
user_id=user_id,
name=f"{user.get('NAME', '')} {user.get('LAST_NAME', '')}",
)
=======
# Step 4: Resolve user
user_id = str(voxi.get("PORTAL_USER_ID", "") or "")
if user_id:
result["crm_user"] = _get_user(client, user_id)
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
return result
# ═══════════════════════════════════════════════════════════════════════════
# 2. "My calls" enrichment
# ═══════════════════════════════════════════════════════════════════════════
<<<<<<< HEAD
def _time_window(
call_datetime: str | None,
) -> tuple[str, str]:
"""Return (since, until) ISO strings for a ±1 day window around the call.
If call_datetime is None, defaults to (now - 2 days, now + 1 hour).
"""
fmt = "%Y-%m-%dT%H:%M:%S+00:00"
if call_datetime:
try:
dt = datetime.strptime(call_datetime, "%Y-%m-%d %H:%M:%S")
except ValueError:
dt = datetime.now(UTC)
since = (dt - timedelta(days=1)).strftime(fmt)
until = (dt + timedelta(days=1)).strftime(fmt)
else:
now = datetime.now(UTC)
since = (now - timedelta(days=2)).strftime(fmt)
until = (now + timedelta(hours=1)).strftime(fmt)
return since, until
def _find_activity(
=======
def enrich_mycall_activity(
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
client: Bitrix24Client,
activity: dict,
) -> dict[str, Any]:
"""Enrich a 'my calls' CRM activity with entity and user data.
Args:
client: Bitrix24Client instance.
activity: Raw activity dict from crm.activity.list.
Returns:
Dict with: crm_activity, crm_entity, crm_entity_type,
crm_company, crm_user.
"""
result: dict[str, Any] = {
"crm_activity": activity,
"crm_entity": None,
"crm_entity_type": None,
"crm_company": None,
"crm_user": None,
}
# Resolve CRM entity by OWNER_TYPE_ID / OWNER_ID
owner_type_id = str(activity.get("OWNER_TYPE_ID", ""))
owner_id = str(activity.get("OWNER_ID", "") or "")
entity_type = _OWNER_TYPE_MAP.get(owner_type_id)
_resolve_entity_chain(client, entity_type, owner_id, result)
# Resolve user
user_id = str(
activity.get("RESPONSIBLE_ID")
or activity.get("AUTHOR_ID")
or ""
)
if user_id:
result["crm_user"] = _get_user(client, user_id)
return result
# ═══════════════════════════════════════════════════════════════════════════
# Shared helpers
# ═══════════════════════════════════════════════════════════════════════════
def _resolve_entity_chain(
client: Bitrix24Client,
entity_type: str | None,
entity_id: str,
result: dict,
) -> None:
"""Resolve CRM entity and its company (if applicable) into *result*."""
if not entity_type or not entity_id or entity_type not in _CRM_ENTITY_METHOD:
return
entity = _get_crm_entity(client, entity_type, entity_id)
if not entity:
return
result["crm_entity"] = entity
result["crm_entity_type"] = entity_type
# If entity has COMPANY_ID, resolve the company too
company_id = str(entity.get("COMPANY_ID", "") or "")
if company_id and entity_type != "COMPANY":
company = _get_crm_entity(client, "COMPANY", company_id)
if company:
result["crm_company"] = company
log.debug("Company resolved",
company_id=company_id, title=company.get("TITLE"))
def _get_activity(client: Bitrix24Client, activity_id: str) -> dict | None:
try:
<<<<<<< HEAD
activities = client.call(
"crm.activity.list",
{
"filter": {
"TYPE_ID": "2",
"%=ORIGIN_ID": f"%{origin_id}%",
">=CREATED": since,
"<=CREATED": until,
},
"select": _ACTIVITY_SELECT,
"order": {"ID": "DESC"},
},
)
if activities and isinstance(activities, list) and activities:
if len(activities) > 1:
log.debug(
"Multiple activities by ORIGIN_ID; using newest",
count=len(activities),
)
return activities[0]
except Bitrix24Error as exc:
log.warning("ORIGIN_ID search failed", error=str(exc))
# --- Try 2: search by phone in SUBJECT ---
if phone and len(phone) >= 7:
phone_suffix = phone[-10:]
log.debug(
"Searching by phone in SUBJECT",
phone=phone_suffix,
since=since,
until=until,
)
try:
activities = client.call(
"crm.activity.list",
{
"filter": {
"TYPE_ID": "2",
"%=SUBJECT": f"%{phone_suffix}%",
">=CREATED": since,
"<=CREATED": until,
},
"select": _ACTIVITY_SELECT,
"order": {"ID": "DESC"},
},
)
if activities and isinstance(activities, list) and activities:
if len(activities) > 1:
log.debug(
"Multiple activities by phone; using newest",
count=len(activities),
)
return activities[0]
except Bitrix24Error as exc:
log.warning("Phone search failed", error=str(exc))
return None
=======
result = client.call("crm.activity.get", {"ID": activity_id})
return result if isinstance(result, dict) else None
except Bitrix24Error as exc:
log.warning("crm.activity.get failed",
activity_id=activity_id, error=str(exc))
return None
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
def _get_crm_entity(
client: Bitrix24Client,
entity_type: str,
entity_id: str,
) -> dict | None:
method = _CRM_ENTITY_METHOD.get(entity_type)
if not method:
return None
try:
result = client.call(method, {"ID": entity_id})
return result if isinstance(result, dict) else None
except Bitrix24Error as exc:
<<<<<<< HEAD
log.warning(
"Failed to fetch CRM entity",
entity_type=entity_type,
entity_id=entity_id,
error=str(exc),
)
=======
log.warning("CRM entity fetch failed",
method=method, entity_id=entity_id, error=str(exc))
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
return None
def _get_user(client: Bitrix24Client, user_id: str) -> dict | None:
try:
result = client.call("user.get", {"ID": user_id})
if isinstance(result, list) and result:
return result[0]
return None
except Bitrix24Error as exc:
<<<<<<< HEAD
log.warning("Failed to fetch user", user_id=user_id, error=str(exc))
return None
=======
log.warning("user.get failed", user_id=user_id, error=str(exc))
return None
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b

View File

@ -1,209 +1,482 @@
from __future__ import annotations
"""collector.bitrix_source — "My calls" pipeline.
Fetches call activities from Bitrix24 via crm.activity.list (TYPE_ID=2),
downloads audio from Bitrix24 Disk, and enriches with CRM entity data.
These are calls made via Bitrix24's built-in telephony or "my calls"
integrations — NOT Asterisk calls (those go through the Asterisk pipeline
and are enriched via voximplant.statistic.get).
"""
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from core.bitrix_client import Bitrix24Client, Bitrix24Error
from core.config import Bitrix24SourceConfig
from core.logger import get_logger
log = get_logger(__name__)
_ACTIVITY_SELECT = [
"ID", "SUBJECT", "CREATED", "START_TIME", "END_TIME",
"COMPLETED", "OWNER_TYPE_ID", "OWNER_ID",
"PROVIDER_ID", "PROVIDER_TYPE_ID", "DIRECTION",
"RESPONSIBLE_ID", "AUTHOR_ID", "ORIGIN_ID",
"COMMUNICATIONS", "STORAGE_ELEMENT_ID",
"ASSOCIATED_ENTITY_ID",
]
@dataclass
class MyCallRecord:
"""A call from crm.activity.list — "my calls" source."""
activity_id: str # Bitrix24 activity ID (used as uniqueid in spool)
activity: dict # Raw activity dict from crm.activity.list
user_id: str | None
caller_phone: str | None
direction: str # "inbound" | "outbound"
duration_s: int | None
entity_type: str | None # "LEAD" | "CONTACT" | "COMPANY" | "DEAL"
entity_id: str | None
created_at: datetime
storage_element_id: str | None # Bitrix24 Disk file ID for audio
enrichment: dict = field(default_factory=dict)
class Bitrix24Source:
"""Fetches "my calls" from Bitrix24 crm.activity.list and downloads audio."""
def __init__(self, cfg: Bitrix24SourceConfig) -> None:
self._cfg = cfg
self._client = Bitrix24Client(
webhook_url=cfg.webhook_url,
retry_attempts=cfg.retry_attempts,
retry_backoff_s=cfg.retry_backoff_s,
)
@property
def client(self) -> Bitrix24Client:
return self._client
def fetch_calls_since(self, since: datetime) -> list[MyCallRecord]:
"""Return all call activities created after *since* (paginated).
Filters:
TYPE_ID = 2 (phone call activities)
CREATED > since
PROVIDER_ID != VOXIMPLANT_CALL (exclude Asterisk/ITGrix calls
which are handled by the Asterisk pipeline)
"""
since_str = since.strftime("%Y-%m-%dT%H:%M:%S")
records: list[MyCallRecord] = []
start = 0
page_size = 50
while True:
try:
activities = self._client.call("crm.activity.list", {
"filter": {
"TYPE_ID": "2",
">CREATED": since_str,
},
"select": _ACTIVITY_SELECT,
"order": {"ID": "ASC"},
"start": start,
})
except Bitrix24Error as exc:
log.error("crm.activity.list failed", error=str(exc), start=start)
break
if not activities or not isinstance(activities, list):
break
for act in activities:
# Skip Voximplant/ITGrix calls — those are Asterisk pipeline
provider = act.get("PROVIDER_ID", "")
if provider == "VOXIMPLANT_CALL":
continue
rec = self._parse_activity(act)
if rec:
records.append(rec)
if len(activities) < page_size:
break # last page
start += page_size
log.info("Fetched 'my calls' activities",
total=len(records), since=since_str)
return records
def _parse_activity(self, act: dict) -> MyCallRecord | None:
"""Parse a raw activity dict into a MyCallRecord."""
try:
activity_id = str(act["ID"])
direction_raw = str(act.get("DIRECTION", "1"))
direction = "inbound" if direction_raw == "1" else "outbound"
user_id = str(act.get("RESPONSIBLE_ID") or act.get("AUTHOR_ID") or "")
user_id = user_id or None
# Phone from COMMUNICATIONS
comms = act.get("COMMUNICATIONS") or []
caller_phone = comms[0].get("VALUE") if comms else None
# Duration from START_TIME / END_TIME
duration_s: int | None = None
start_time = act.get("START_TIME")
end_time = act.get("END_TIME")
if start_time and end_time:
try:
st = datetime.fromisoformat(start_time)
et = datetime.fromisoformat(end_time)
duration_s = int((et - st).total_seconds())
except (ValueError, TypeError):
pass
# Owner entity
owner_type_map = {"1": "LEAD", "2": "DEAL", "3": "CONTACT", "4": "COMPANY"}
entity_type = owner_type_map.get(str(act.get("OWNER_TYPE_ID", "")))
entity_id = str(act.get("OWNER_ID") or "") or None
# Storage element for audio download
storage_id = str(act.get("STORAGE_ELEMENT_ID") or "") or None
created_at = datetime.fromisoformat(
act["CREATED"]
).replace(tzinfo=timezone.utc)
return MyCallRecord(
activity_id=activity_id,
activity=act,
user_id=user_id,
caller_phone=caller_phone,
direction=direction,
duration_s=duration_s,
entity_type=entity_type,
entity_id=entity_id,
created_at=created_at,
storage_element_id=storage_id,
)
except (KeyError, ValueError) as exc:
log.warning("Failed to parse activity",
activity_id=act.get("ID"), error=str(exc))
return None
def download_audio(self, record: MyCallRecord, dest_dir: Path) -> Path | None:
"""Download the audio file for a "my call" record.
Uses STORAGE_ELEMENT_ID → disk.file.get to get the download URL.
Returns the local path, or None if no audio available.
"""
if not record.storage_element_id:
log.debug("No STORAGE_ELEMENT_ID; skipping download",
activity_id=record.activity_id)
return None
# Get download URL from Bitrix24 Disk
try:
download_url = self._client.get_file_download_url(
record.storage_element_id
)
except (Bitrix24Error, Exception) as exc:
log.warning("Failed to get download URL",
storage_id=record.storage_element_id, error=str(exc))
return None
if not download_url:
log.debug("Empty download URL", storage_id=record.storage_element_id)
return None
# Download the file
try:
data = self._client.download_file(download_url)
except (Bitrix24Error, Exception) as exc:
log.warning("Failed to download audio",
activity_id=record.activity_id, error=str(exc))
return None
dest_dir.mkdir(parents=True, exist_ok=True)
local_path = dest_dir / "audio.mp3"
local_path.write_bytes(data)
log.info("Audio downloaded",
activity_id=record.activity_id, bytes=len(data))
from __future__ import annotations
<<<<<<< HEAD
from dataclasses import dataclass
from datetime import UTC, date, datetime
=======
"""collector.bitrix_source — "My calls" pipeline.
Fetches call activities from Bitrix24 via crm.activity.list (TYPE_ID=2),
downloads audio from Bitrix24 Disk, and enriches with CRM entity data.
These are calls made via Bitrix24's built-in telephony or "my calls"
integrations — NOT Asterisk calls (those go through the Asterisk pipeline
and are enriched via voximplant.statistic.get).
"""
from dataclasses import dataclass, field
from datetime import datetime, timezone
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
from pathlib import Path
from typing import Any
from core.bitrix_client import Bitrix24Client, Bitrix24Error
from core.config import Bitrix24SourceConfig
from core.logger import get_logger
log = get_logger(__name__)
_ACTIVITY_SELECT = [
"ID", "SUBJECT", "CREATED", "START_TIME", "END_TIME",
"COMPLETED", "OWNER_TYPE_ID", "OWNER_ID",
"PROVIDER_ID", "PROVIDER_TYPE_ID", "DIRECTION",
"RESPONSIBLE_ID", "AUTHOR_ID", "ORIGIN_ID",
"COMMUNICATIONS", "STORAGE_ELEMENT_ID",
"ASSOCIATED_ENTITY_ID",
]
@dataclass
<<<<<<< HEAD
class Bitrix24CallRecord:
"""Normalized call activity extracted from Bitrix24 CRM."""
uniqueid: str
activity_id: str
source: str # "asterisk" | "my_calls" | "unknown"
origin_id: str | None
external_call_id: str | None
user_id: str | None
caller_phone: str | None
direction: str # "inbound" | "outbound"
=======
class MyCallRecord:
"""A call from crm.activity.list — "my calls" source."""
activity_id: str # Bitrix24 activity ID (used as uniqueid in spool)
activity: dict # Raw activity dict from crm.activity.list
user_id: str | None
caller_phone: str | None
direction: str # "inbound" | "outbound"
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
duration_s: int | None
entity_type: str | None # "LEAD" | "CONTACT" | "COMPANY" | "DEAL"
entity_id: str | None
contact_id: str | None
lead_id: str | None
company_id: str | None
created_at: datetime
<<<<<<< HEAD
call_start_at: datetime | None
raw_activity: dict[str, Any]
=======
storage_element_id: str | None # Bitrix24 Disk file ID for audio
enrichment: dict = field(default_factory=dict)
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
class Bitrix24Source:
"""Fetches "my calls" from Bitrix24 crm.activity.list and downloads audio."""
def __init__(self, cfg: Bitrix24SourceConfig) -> None:
self._cfg = cfg
self._client = Bitrix24Client(
webhook_url=cfg.webhook_url,
retry_attempts=cfg.retry_attempts,
retry_backoff_s=cfg.retry_backoff_s,
)
<<<<<<< HEAD
def fetch_calls_since(self, since: datetime) -> list[Bitrix24CallRecord]:
"""Legacy incremental mode: return all call activities created after *since* (UTC)."""
=======
@property
def client(self) -> Bitrix24Client:
return self._client
def fetch_calls_since(self, since: datetime) -> list[MyCallRecord]:
"""Return all call activities created after *since* (paginated).
Filters:
TYPE_ID = 2 (phone call activities)
CREATED > since
PROVIDER_ID != VOXIMPLANT_CALL (exclude Asterisk/ITGrix calls
which are handled by the Asterisk pipeline)
"""
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
since_str = since.strftime("%Y-%m-%dT%H:%M:%S")
records: list[MyCallRecord] = []
start = 0
page_size = 50
while True:
<<<<<<< HEAD
activities = self._client.activity_list(
filter_={
"TYPE_ID": "2",
">CREATED": since_str,
},
select=self._activity_select(),
start=start,
)
if not activities:
=======
try:
activities = self._client.call("crm.activity.list", {
"filter": {
"TYPE_ID": "2",
">CREATED": since_str,
},
"select": _ACTIVITY_SELECT,
"order": {"ID": "ASC"},
"start": start,
})
except Bitrix24Error as exc:
log.error("crm.activity.list failed", error=str(exc), start=start)
break
if not activities or not isinstance(activities, list):
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
break
for act in activities:
# Skip Voximplant/ITGrix calls — those are Asterisk pipeline
provider = act.get("PROVIDER_ID", "")
if provider == "VOXIMPLANT_CALL":
continue
rec = self._parse_activity(act)
if rec:
records.append(rec)
<<<<<<< HEAD
if len(activities) < self._cfg.page_size:
break
start += self._cfg.page_size
log.info(
"Fetched Bitrix24 call activities", count=len(records), since=since_str
)
return records
def fetch_calls_for_date(self, day: date) -> list[Bitrix24CallRecord]:
"""Date-driven mode: return all CRM call activities for the specified calendar date."""
start_str = f"{day:%Y-%m-%d}T00:00:00"
stop_str = f"{day:%Y-%m-%d}T23:59:59"
records: list[Bitrix24CallRecord] = []
start = 0
while True:
activities = self._client.call(
"crm.activity.list",
{
"filter": {
"TYPE_ID": "2",
">=CALL_START_DATE": start_str,
"<=CALL_STOP_DATE": stop_str,
},
"select": self._activity_select(),
"order": {"CALL_START_DATE": "ASC", "ID": "ASC"},
"start": start,
},
)
if not activities:
break
for act in activities:
rec = self._parse_activity(act)
if rec:
records.append(rec)
if len(activities) < self._cfg.page_size:
break
start += self._cfg.page_size
log.info(
"Fetched Bitrix24 call activities for date",
count=len(records),
date=str(day),
)
return records
def _activity_select(self) -> list[str]:
return [
"ID",
"CREATED",
"CALL_START_DATE",
"CALL_STOP_DATE",
"DIRECTION",
"OWNER_TYPE_ID",
"OWNER_ID",
"RESPONSIBLE_ID",
"AUTHOR_ID",
"COMMUNICATIONS",
"ASSOCIATED_ENTITY_ID",
"STORAGE_ELEMENT_ID",
"ORIGIN_ID",
"PROVIDER_ID",
"PROVIDER_TYPE_ID",
]
def _parse_activity(self, act: dict) -> Bitrix24CallRecord | None:
try:
activity_id = str(act["ID"])
origin_id = str(act.get("ORIGIN_ID")) if act.get("ORIGIN_ID") else None
external_call_id = origin_id or (
str(act.get("ASSOCIATED_ENTITY_ID"))
if act.get("ASSOCIATED_ENTITY_ID")
else None
)
source = self._detect_source(act)
uniqueid = self._build_uniqueid(source, activity_id, external_call_id)
direction = (
"inbound" if str(act.get("DIRECTION", "1")) == "1" else "outbound"
)
user_id = (
str(act.get("RESPONSIBLE_ID") or act.get("AUTHOR_ID"))
if (act.get("RESPONSIBLE_ID") or act.get("AUTHOR_ID"))
else None
)
comms = act.get("COMMUNICATIONS") or []
caller_phone = comms[0].get("VALUE") if comms else None
=======
if len(activities) < page_size:
break # last page
start += page_size
log.info("Fetched 'my calls' activities",
total=len(records), since=since_str)
return records
def _parse_activity(self, act: dict) -> MyCallRecord | None:
"""Parse a raw activity dict into a MyCallRecord."""
try:
activity_id = str(act["ID"])
direction_raw = str(act.get("DIRECTION", "1"))
direction = "inbound" if direction_raw == "1" else "outbound"
user_id = str(act.get("RESPONSIBLE_ID") or act.get("AUTHOR_ID") or "")
user_id = user_id or None
# Phone from COMMUNICATIONS
comms = act.get("COMMUNICATIONS") or []
caller_phone = comms[0].get("VALUE") if comms else None
# Duration from START_TIME / END_TIME
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
duration_s: int | None = None
start_time = act.get("START_TIME")
end_time = act.get("END_TIME")
if start_time and end_time:
try:
st = datetime.fromisoformat(start_time)
et = datetime.fromisoformat(end_time)
duration_s = int((et - st).total_seconds())
except (ValueError, TypeError):
pass
<<<<<<< HEAD
entity_type, entity_id, contact_id, lead_id, company_id = (
self._resolve_links(act)
)
mp3_url: str | None = None
storage_id = act.get("STORAGE_ELEMENT_ID")
if storage_id:
mp3_url = self._client.get_file_download_url(str(storage_id))
created_at = self._parse_dt(act.get("CREATED")) or datetime.now(UTC)
call_start_at = self._parse_dt(
act.get("CALL_START_DATE") or act.get("START_TIME")
)
return Bitrix24CallRecord(
uniqueid=uniqueid,
activity_id=activity_id,
source=source,
origin_id=origin_id,
external_call_id=external_call_id,
=======
# Owner entity
owner_type_map = {"1": "LEAD", "2": "DEAL", "3": "CONTACT", "4": "COMPANY"}
entity_type = owner_type_map.get(str(act.get("OWNER_TYPE_ID", "")))
entity_id = str(act.get("OWNER_ID") or "") or None
# Storage element for audio download
storage_id = str(act.get("STORAGE_ELEMENT_ID") or "") or None
created_at = datetime.fromisoformat(
act["CREATED"]
).replace(tzinfo=timezone.utc)
return MyCallRecord(
activity_id=activity_id,
activity=act,
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
user_id=user_id,
caller_phone=caller_phone,
direction=direction,
duration_s=duration_s,
entity_type=entity_type,
entity_id=entity_id,
contact_id=contact_id,
lead_id=lead_id,
company_id=company_id,
created_at=created_at,
<<<<<<< HEAD
call_start_at=call_start_at,
raw_activity=act,
)
except (KeyError, ValueError) as exc:
log.warning(
"Failed to parse Bitrix24 activity",
error=str(exc),
activity_id=act.get("ID"),
)
return None
def _detect_source(self, act: dict) -> str:
provider_id = str(act.get("PROVIDER_ID") or "").lower()
provider_type_id = str(act.get("PROVIDER_TYPE_ID") or "").lower()
origin_id = str(act.get("ORIGIN_ID") or "")
storage_id = act.get("STORAGE_ELEMENT_ID")
if "asterisk" in provider_id or "asterisk" in provider_type_id:
return "asterisk"
if storage_id:
return "my_calls"
if origin_id and (
"externalcall" in origin_id.lower() or "asterisk" in origin_id.lower()
):
return "asterisk"
if act.get("ASSOCIATED_ENTITY_ID"):
return "my_calls"
return "unknown"
def _build_uniqueid(
self, source: str, activity_id: str, external_call_id: str | None
) -> str:
if source == "my_calls" and external_call_id:
return f"my_calls:{external_call_id}"
if source == "asterisk" and external_call_id:
return f"asterisk:{external_call_id}"
return f"crm:{activity_id}"
def _resolve_links(
self, act: dict
) -> tuple[str | None, str | None, str | None, str | None, str | None]:
owner_type_id = str(act.get("OWNER_TYPE_ID") or "")
owner_id = str(act.get("OWNER_ID")) if act.get("OWNER_ID") else None
owner_type_map = {
"1": "LEAD",
"2": "DEAL",
"3": "CONTACT",
"4": "COMPANY",
}
entity_type = owner_type_map.get(owner_type_id)
entity_id = owner_id
contact_id = None
lead_id = None
company_id = None
if entity_type == "LEAD":
lead_id = owner_id
elif entity_type == "CONTACT":
contact_id = owner_id
elif entity_type == "COMPANY":
company_id = owner_id
return entity_type, entity_id, contact_id, lead_id, company_id
def _parse_dt(self, value: str | None) -> datetime | None:
if not value:
return None
try:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
=======
storage_element_id=storage_id,
)
except (KeyError, ValueError) as exc:
log.warning("Failed to parse activity",
activity_id=act.get("ID"), error=str(exc))
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
return None
def download_audio(self, record: MyCallRecord, dest_dir: Path) -> Path | None:
"""Download the audio file for a "my call" record.
<<<<<<< HEAD
def get_voximplant_stat(self, record: Bitrix24CallRecord) -> dict | None:
"""Load Voximplant stats for one call.
Filter names may need tuning for the target portal.
"""
filters: dict[str, Any] = {}
if record.external_call_id:
filters["CALL_ID"] = record.external_call_id
elif record.activity_id:
filters["CRM_ACTIVITY_ID"] = record.activity_id
elif record.caller_phone:
filters["PHONE_NUMBER"] = record.caller_phone
if record.call_start_at:
filters["CALL_START_DATE"] = record.call_start_at.strftime(
"%Y-%m-%dT%H:%M:%S"
)
if not filters:
return None
result = self._client.call("voximplant.statistic.get", {"FILTER": filters})
if isinstance(result, list) and result:
return result[0]
if isinstance(result, dict):
items = (
result.get("result") if isinstance(result.get("result"), list) else None
)
if items:
return items[0]
return None
def download_mp3(self, record: Bitrix24CallRecord, dest_dir: Path) -> Path | None:
if not record.mp3_download_url:
log.warning("No MP3 download URL", uniqueid=record.uniqueid)
=======
Uses STORAGE_ELEMENT_ID → disk.file.get to get the download URL.
Returns the local path, or None if no audio available.
"""
if not record.storage_element_id:
log.debug("No STORAGE_ELEMENT_ID; skipping download",
activity_id=record.activity_id)
return None
# Get download URL from Bitrix24 Disk
try:
download_url = self._client.get_file_download_url(
record.storage_element_id
)
except (Bitrix24Error, Exception) as exc:
log.warning("Failed to get download URL",
storage_id=record.storage_element_id, error=str(exc))
return None
if not download_url:
log.debug("Empty download URL", storage_id=record.storage_element_id)
return None
# Download the file
try:
data = self._client.download_file(download_url)
except (Bitrix24Error, Exception) as exc:
log.warning("Failed to download audio",
activity_id=record.activity_id, error=str(exc))
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
return None
dest_dir.mkdir(parents=True, exist_ok=True)
local_path = dest_dir / "audio.mp3"
local_path.write_bytes(data)
log.info("Audio downloaded",
activity_id=record.activity_id, bytes=len(data))
return local_path

View File

@ -1,135 +1,135 @@
from __future__ import annotations
"""collector.filename_parser — Parse Asterisk recording filenames.
Filename structure (from MixMonitor dialplan):
<route_direction>-<calling>-<called>-<YYYYMMDD>-<HHMMSS>-<ORIGIN_ID>.<ORIGIN_ID_suffix>(|-rx|-tx).WAV
Examples:
external-1198-89874967783-20260623-154449-1782211489.118028.WAV
in-2798088-83472281747-20260623-100603-1782191163.112633-rx.WAV
out-8(917) 478-62-15-1151-20260623-112018-1782195617.113627-tx.WAV
internal-1102-1144-20260623-111330-1782195210.113537.WAV
Parsing strategy (anchored from the end, which is always well-formed):
1. Strip .WAV and optional -rx/-tx suffix
2. From the end: ORIGIN_ID.suffix (digits.digits)
3. Then: HHMMSS (6 digits)
4. Then: YYYYMMDD (8 digits)
5. Remaining prefix: split on dashes
- First token = route_direction
- Last token = called (destination extension or number)
- Middle tokens = calling (source; may contain dashes in malformed numbers)
"""
import re
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from core.logger import get_logger
log = get_logger(__name__)
_STEM_PATTERN = re.compile(
r"^(?P<prefix>.+)-(?P<date>\d{8})-(?P<time>\d{6})-(?P<uid>\d+)\.(?P<uid_suffix>\d+)$"
)
@dataclass
class AsteriskFileInfo:
"""Structured fields extracted from an Asterisk recording filename."""
original_filename: str
route_direction: str # "external" | "internal" | "in" | "out"
calling: str # caller (extension or phone number)
called: str # callee (extension or phone number)
call_date: str # "YYYYMMDD"
call_time: str # "HHMMSS"
call_datetime: str # "YYYY-MM-DD HH:MM:SS"
origin_id: str # Asterisk epoch part of UNIQUEID, e.g. "1782211489"
origin_id_suffix: str # Asterisk sequence part, e.g. "118028"
uniqueid: str # Full UNIQUEID: "1782211489.118028"
def to_dict(self) -> dict:
return {
"original_filename": self.original_filename,
"route_direction": self.route_direction,
"calling": self.calling,
"called": self.called,
"call_date": self.call_date,
"call_time": self.call_time,
"call_datetime": self.call_datetime,
"origin_id": self.origin_id,
"origin_id_suffix": self.origin_id_suffix,
"uniqueid": self.uniqueid,
}
def parse_asterisk_filename(filename: str) -> AsteriskFileInfo | None:
"""Parse an Asterisk recording filename into structured fields.
Args:
filename: Bare filename or relative path. Only the filename part
(Path.name) is parsed; directory components are ignored.
Returns:
AsteriskFileInfo on success, None if the filename doesn't match
the expected Asterisk format.
"""
bare = Path(filename).name
stem = bare
# Strip .WAV (case-insensitive)
if stem.upper().endswith(".WAV"):
stem = stem[:-4]
else:
return None
# Strip optional -rx / -tx channel suffix
stem = re.sub(r"-(rx|tx)$", "", stem, flags=re.IGNORECASE)
# Match the well-structured tail: YYYYMMDD-HHMMSS-ORIGIN_ID.SUFFIX
m = _STEM_PATTERN.match(stem)
if not m:
log.debug("Filename does not match Asterisk pattern", filename=bare)
return None
prefix = m.group("prefix")
date_str = m.group("date")
time_str = m.group("time")
uid = m.group("uid")
uid_suffix = m.group("uid_suffix")
# Parse prefix: route_direction - calling - called
# First token is always route_direction.
# Last token is always called (destination).
# Everything in between is calling (may contain dashes in rare cases).
parts = prefix.split("-")
if len(parts) < 3:
log.debug("Prefix has too few segments", prefix=prefix, filename=bare)
return None
route_direction = parts[0]
called = parts[-1]
calling = "-".join(parts[1:-1])
# Format datetime
try:
dt = datetime.strptime(f"{date_str}{time_str}", "%Y%m%d%H%M%S")
call_datetime = dt.strftime("%Y-%m-%d %H:%M:%S")
except ValueError:
call_datetime = f"{date_str} {time_str}"
return AsteriskFileInfo(
original_filename=bare,
route_direction=route_direction,
calling=calling,
called=called,
call_date=date_str,
call_time=time_str,
call_datetime=call_datetime,
origin_id=uid,
origin_id_suffix=uid_suffix,
uniqueid=f"{uid}.{uid_suffix}",
)
from __future__ import annotations
"""collector.filename_parser — Parse Asterisk recording filenames.
Filename structure (from MixMonitor dialplan):
<route_direction>-<calling>-<called>-<YYYYMMDD>-<HHMMSS>-<ORIGIN_ID>.<ORIGIN_ID_suffix>(|-rx|-tx).WAV
Examples:
external-1198-89874967783-20260623-154449-1782211489.118028.WAV
in-2798088-83472281747-20260623-100603-1782191163.112633-rx.WAV
out-8(917) 478-62-15-1151-20260623-112018-1782195617.113627-tx.WAV
internal-1102-1144-20260623-111330-1782195210.113537.WAV
Parsing strategy (anchored from the end, which is always well-formed):
1. Strip .WAV and optional -rx/-tx suffix
2. From the end: ORIGIN_ID.suffix (digits.digits)
3. Then: HHMMSS (6 digits)
4. Then: YYYYMMDD (8 digits)
5. Remaining prefix: split on dashes
- First token = route_direction
- Last token = called (destination extension or number)
- Middle tokens = calling (source; may contain dashes in malformed numbers)
"""
import re
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from core.logger import get_logger
log = get_logger(__name__)
_STEM_PATTERN = re.compile(
r"^(?P<prefix>.+)-(?P<date>\d{8})-(?P<time>\d{6})-(?P<uid>\d+)\.(?P<uid_suffix>\d+)$"
)
@dataclass
class AsteriskFileInfo:
"""Structured fields extracted from an Asterisk recording filename."""
original_filename: str
route_direction: str # "external" | "internal" | "in" | "out"
calling: str # caller (extension or phone number)
called: str # callee (extension or phone number)
call_date: str # "YYYYMMDD"
call_time: str # "HHMMSS"
call_datetime: str # "YYYY-MM-DD HH:MM:SS"
origin_id: str # Asterisk epoch part of UNIQUEID, e.g. "1782211489"
origin_id_suffix: str # Asterisk sequence part, e.g. "118028"
uniqueid: str # Full UNIQUEID: "1782211489.118028"
def to_dict(self) -> dict:
return {
"original_filename": self.original_filename,
"route_direction": self.route_direction,
"calling": self.calling,
"called": self.called,
"call_date": self.call_date,
"call_time": self.call_time,
"call_datetime": self.call_datetime,
"origin_id": self.origin_id,
"origin_id_suffix": self.origin_id_suffix,
"uniqueid": self.uniqueid,
}
def parse_asterisk_filename(filename: str) -> AsteriskFileInfo | None:
"""Parse an Asterisk recording filename into structured fields.
Args:
filename: Bare filename or relative path. Only the filename part
(Path.name) is parsed; directory components are ignored.
Returns:
AsteriskFileInfo on success, None if the filename doesn't match
the expected Asterisk format.
"""
bare = Path(filename).name
stem = bare
# Strip .WAV (case-insensitive)
if stem.upper().endswith(".WAV"):
stem = stem[:-4]
else:
return None
# Strip optional -rx / -tx channel suffix
stem = re.sub(r"-(rx|tx)$", "", stem, flags=re.IGNORECASE)
# Match the well-structured tail: YYYYMMDD-HHMMSS-ORIGIN_ID.SUFFIX
m = _STEM_PATTERN.match(stem)
if not m:
log.debug("Filename does not match Asterisk pattern", filename=bare)
return None
prefix = m.group("prefix")
date_str = m.group("date")
time_str = m.group("time")
uid = m.group("uid")
uid_suffix = m.group("uid_suffix")
# Parse prefix: route_direction - calling - called
# First token is always route_direction.
# Last token is always called (destination).
# Everything in between is calling (may contain dashes in rare cases).
parts = prefix.split("-")
if len(parts) < 3:
log.debug("Prefix has too few segments", prefix=prefix, filename=bare)
return None
route_direction = parts[0]
called = parts[-1]
calling = "-".join(parts[1:-1])
# Format datetime
try:
dt = datetime.strptime(f"{date_str}{time_str}", "%Y%m%d%H%M%S")
call_datetime = dt.strftime("%Y-%m-%d %H:%M:%S")
except ValueError:
call_datetime = f"{date_str} {time_str}"
return AsteriskFileInfo(
original_filename=bare,
route_direction=route_direction,
calling=calling,
called=called,
call_date=date_str,
call_time=time_str,
call_datetime=call_datetime,
origin_id=uid,
origin_id_suffix=uid_suffix,
uniqueid=f"{uid}.{uid_suffix}",
)

File diff suppressed because it is too large Load Diff

View File

@ -1,268 +1,344 @@
from __future__ import annotations
import json
import os
import shutil
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from core.config import get_config
from core.logger import get_logger
from core.models import CallDirection, CallSource, CallStatus
log = get_logger(__name__)
_CHECKPOINT_FILENAME = ".collector_checkpoint"
_STAGING_DIR = ".staging"
# ---------------------------------------------------------------------------
# Staging area — temp dirs on the SAME filesystem as the spool
# ---------------------------------------------------------------------------
def _get_staging_dir() -> Path:
"""Return (and create) a staging directory inside spool_root.
Because staging and spool live on the same filesystem, os.rename()
works atomically — no cross-device errors.
"""
cfg = get_config()
staging = cfg.storage.spool_root / _STAGING_DIR
staging.mkdir(parents=True, exist_ok=True)
return staging
def make_staging_tmpdir(prefix: str = "vp-") -> Path:
"""Create a temporary directory inside spool_root/.staging/.
Returns the Path. Caller is responsible for cleanup (or it will be
cleaned up by spool_asterisk_set via os.rename).
"""
staging = _get_staging_dir()
return Path(tempfile.mkdtemp(prefix=prefix, dir=staging))
# ---------------------------------------------------------------------------
# Checkpoint
# ---------------------------------------------------------------------------
def load_checkpoint(spool_root: Path, pipeline: str = "default") -> datetime:
"""Return the last successful collection timestamp (UTC) for *pipeline*.
Each pipeline has its own checkpoint file so they don't interfere.
Defaults to 24 hours ago if no checkpoint file exists.
"""
path = spool_root / f".checkpoint_{pipeline}"
if path.exists():
raw = path.read_text().strip()
try:
return datetime.fromisoformat(raw).replace(tzinfo=timezone.utc)
except ValueError:
log.warning("Corrupt checkpoint file; resetting", path=str(path))
from datetime import timedelta
default = datetime.now(timezone.utc) - timedelta(hours=24)
log.info("No checkpoint found; using default lookback",
pipeline=pipeline, since=default.isoformat())
return default
def save_checkpoint(spool_root: Path, ts: datetime, pipeline: str = "default") -> None:
"""Atomically write the checkpoint timestamp for *pipeline*."""
path = spool_root / f".checkpoint_{pipeline}"
tmp = path.with_suffix(".tmp")
tmp.write_text(ts.isoformat())
os.rename(tmp, path) # same dir, same FS — always works
log.debug("Checkpoint saved", pipeline=pipeline, ts=ts.isoformat())
# ---------------------------------------------------------------------------
# Meta.json helpers
# ---------------------------------------------------------------------------
def _write_atomic(path: Path, data: dict) -> None:
"""Write JSON to *path* atomically (temp file → rename).
The .tmp file is created in the same directory as *path*, so
os.rename() never crosses filesystems.
"""
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
os.rename(tmp, path)
def read_meta(spool_dir: Path) -> dict:
return json.loads((spool_dir / "meta.json").read_text(encoding="utf-8"))
def update_meta_status(spool_dir: Path, status: str, error: str | None = None) -> None:
"""Read meta.json, update status (and optionally last_error), write back atomically."""
meta = read_meta(spool_dir)
meta["status"] = status
if error is not None:
meta["last_error"] = error
_write_atomic(spool_dir / "meta.json", meta)
def _extract_call_date(relative_path: str) -> str | None:
"""Extract a YYYY-MM-DD date string from an Asterisk relative path.
Asterisk stores files in YYYY/MM/DD/ directories. Given a relative path
like "2026/06/23/external-...-rx.WAV", returns "2026-06-23".
Returns None if the path doesn't contain a valid date prefix.
"""
parts = relative_path.replace("\\", "/").split("/")
if len(parts) >= 3:
try:
# Validate it's a real date
datetime.strptime(f"{parts[0]}-{parts[1]}-{parts[2]}", "%Y-%m-%d")
return f"{parts[0]}-{parts[1]}-{parts[2]}"
except ValueError:
pass
return None
# ---------------------------------------------------------------------------
# Asterisk spool
# ---------------------------------------------------------------------------
def spool_asterisk_set(
uniqueid: str,
tmp_dir: Path,
*,
call_date: str | None = None,
direction: str = CallDirection.UNKNOWN,
duration_s: int | None = None,
caller_phone: str | None = None,
user_id: str | None = None,
entity_type: str | None = None,
entity_id: str | None = None,
asterisk_meta: dict | None = None,
bitrix24_enrichment: dict | None = None,
) -> Path:
"""Atomically move a downloaded WAV set from *tmp_dir* into the spool.
Args:
call_date: Date of the call as "YYYY-MM-DD".
asterisk_meta: Parsed filename fields (from filename_parser).
bitrix24_enrichment: CRM enrichment data (from bitrix_enrichment).
*tmp_dir* must already contain mixed.wav, rx.wav, tx.wav.
Returns the final spool directory path.
"""
cfg = get_config()
date_str = call_date or datetime.now(timezone.utc).strftime("%Y-%m-%d")
spool_dir = cfg.storage.spool_root / date_str / uniqueid
if spool_dir.exists():
log.warning("Spool dir already exists; skipping", uniqueid=uniqueid, path=str(spool_dir))
return spool_dir
# Validate all 3 WAVs are present in tmp_dir
for name in ("mixed.wav", "rx.wav", "tx.wav"):
if not (tmp_dir / name).exists():
raise FileNotFoundError(f"Missing {name} in temp dir {tmp_dir}")
# Move temp dir into place — same filesystem, so os.rename is atomic
spool_dir.parent.mkdir(parents=True, exist_ok=True)
try:
os.rename(tmp_dir, spool_dir)
except OSError:
log.warning("Cross-device rename; falling back to shutil.move",
src=str(tmp_dir), dst=str(spool_dir))
shutil.move(str(tmp_dir), str(spool_dir))
# Build meta.json with all available data
meta: dict = {
"uniqueid": uniqueid,
"source": CallSource.ASTERISK,
"has_rx_tx": True,
"direction": direction,
"duration_s": duration_s,
"caller_phone": caller_phone,
"user_id": user_id,
"entity_type": entity_type,
"entity_id": entity_id,
"fetched_at": datetime.now(timezone.utc).isoformat(),
"status": CallStatus.SPOOLED,
}
# Add parsed Asterisk filename fields
if asterisk_meta:
meta["asterisk"] = asterisk_meta
# Add Bitrix24 enrichment (activity, CRM entity, company, user)
if bitrix24_enrichment:
meta["bitrix24"] = bitrix24_enrichment
# Write meta.json last (readiness signal)
_write_atomic(spool_dir / "meta.json", meta)
log.info("Asterisk WAV set spooled", uniqueid=uniqueid, spool_dir=str(spool_dir))
return spool_dir
# ---------------------------------------------------------------------------
# Bitrix24 spool
# ---------------------------------------------------------------------------
def spool_bitrix24_call(
uniqueid: str,
mp3_path: Path,
*,
call_date: str | None = None,
direction: str = CallDirection.UNKNOWN,
duration_s: int | None = None,
caller_phone: str | None = None,
user_id: str | None = None,
entity_type: str | None = None,
entity_id: str | None = None,
bitrix24_enrichment: dict | None = None,
) -> Path:
"""Move a downloaded MP3 into the spool and write meta.json.
Returns the final spool directory path.
"""
cfg = get_config()
date_str = call_date or datetime.now(timezone.utc).strftime("%Y-%m-%d")
spool_dir = cfg.storage.spool_root / date_str / uniqueid
if spool_dir.exists():
log.warning("Spool dir already exists; skipping", uniqueid=uniqueid)
return spool_dir
spool_dir.mkdir(parents=True, exist_ok=True)
# Move the MP3 into the spool dir
dest_mp3 = spool_dir / "audio.mp3"
try:
os.rename(mp3_path, dest_mp3)
except OSError:
shutil.move(str(mp3_path), str(dest_mp3))
# Write meta.json
meta: dict = {
"uniqueid": uniqueid,
"source": CallSource.BITRIX24,
"has_rx_tx": False,
"direction": direction,
"duration_s": duration_s,
"caller_phone": caller_phone,
"user_id": user_id,
"entity_type": entity_type,
"entity_id": entity_id,
"fetched_at": datetime.now(timezone.utc).isoformat(),
"status": CallStatus.SPOOLED,
}
if bitrix24_enrichment:
meta["bitrix24"] = bitrix24_enrichment
_write_atomic(spool_dir / "meta.json", meta)
log.info("Bitrix24 call spooled", uniqueid=uniqueid, spool_dir=str(spool_dir))
from __future__ import annotations
import json
import os
import shutil
import tempfile
from datetime import UTC, datetime
from pathlib import Path
from core.config import get_config
from core.logger import get_logger
from core.models import CallDirection, CallSource, CallStatus
log = get_logger(__name__)
_CHECKPOINT_FILENAME = ".collector_checkpoint"
_STAGING_DIR = ".staging"
# ---------------------------------------------------------------------------
# Staging area — temp dirs on the SAME filesystem as the spool
# ---------------------------------------------------------------------------
def _get_staging_dir() -> Path:
"""Return (and create) a staging directory inside spool_root.
Because staging and spool live on the same filesystem, os.rename()
works atomically — no cross-device errors.
"""
cfg = get_config()
staging = cfg.storage.spool_root / _STAGING_DIR
staging.mkdir(parents=True, exist_ok=True)
return staging
def make_staging_tmpdir(prefix: str = "vp-") -> Path:
"""Create a temporary directory inside spool_root/.staging/.
Returns the Path. Caller is responsible for cleanup (or it will be
cleaned up by spool_asterisk_set via os.rename).
"""
staging = _get_staging_dir()
return Path(tempfile.mkdtemp(prefix=prefix, dir=staging))
# ---------------------------------------------------------------------------
# Checkpoint
# ---------------------------------------------------------------------------
def load_checkpoint(spool_root: Path, pipeline: str = "default") -> datetime:
"""Return the last successful collection timestamp (UTC) for *pipeline*.
Each pipeline has its own checkpoint file so they don't interfere.
Defaults to 24 hours ago if no checkpoint file exists.
"""
path = spool_root / f".checkpoint_{pipeline}"
if path.exists():
raw = path.read_text().strip()
try:
return datetime.fromisoformat(raw).replace(tzinfo=UTC)
except ValueError:
log.warning("Corrupt checkpoint file; resetting", path=str(path))
from datetime import timedelta
<<<<<<< HEAD
default = datetime.now(UTC) - timedelta(hours=24)
log.info("No checkpoint found; using default lookback", since=default.isoformat())
=======
default = datetime.now(timezone.utc) - timedelta(hours=24)
log.info("No checkpoint found; using default lookback",
pipeline=pipeline, since=default.isoformat())
>>>>>>> 9c4cc76edd455714aa99eb3fb2a0e659c33aac1b
return default
def save_checkpoint(spool_root: Path, ts: datetime, pipeline: str = "default") -> None:
"""Atomically write the checkpoint timestamp for *pipeline*."""
path = spool_root / f".checkpoint_{pipeline}"
tmp = path.with_suffix(".tmp")
tmp.write_text(ts.isoformat())
os.rename(tmp, path) # same dir, same FS — always works
log.debug("Checkpoint saved", pipeline=pipeline, ts=ts.isoformat())
# ---------------------------------------------------------------------------
# Meta.json helpers
# ---------------------------------------------------------------------------
def _write_atomic(path: Path, data: dict) -> None:
"""Write JSON to *path* atomically (temp file → rename).
The .tmp file is created in the same directory as *path*, so
os.rename() never crosses filesystems.
"""
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
os.rename(tmp, path)
def read_meta(spool_dir: Path) -> dict:
return json.loads((spool_dir / "meta.json").read_text(encoding="utf-8"))
def update_meta_status(spool_dir: Path, status: str, error: str | None = None) -> None:
"""Read meta.json, update status (and optionally last_error), write back atomically."""
meta = read_meta(spool_dir)
meta["status"] = status
if error is not None:
meta["last_error"] = error
_write_atomic(spool_dir / "meta.json", meta)
def canonicalize_direction(direction: str | None) -> str:
normalized = (direction or "").strip().lower()
if normalized in {
CallDirection.INBOUND,
CallDirection.OUTBOUND,
CallDirection.UNKNOWN,
}:
return normalized
return CallDirection.UNKNOWN
def channel_roles_for_direction(direction: str) -> dict[str, str]:
match canonicalize_direction(direction):
case CallDirection.INBOUND:
return {"rx": "agent", "tx": "customer"}
case CallDirection.OUTBOUND:
return {"rx": "customer", "tx": "agent"}
case _:
return {"rx": "unknown", "tx": "unknown"}
def _extract_call_date(relative_path: str) -> str | None:
"""Extract a YYYY-MM-DD date string from an Asterisk relative path.
Asterisk stores files in YYYY/MM/DD/ directories. Given a relative path
like "2026/06/23/external-...-rx.WAV", returns "2026-06-23".
Returns None if the path doesn't contain a valid date prefix.
"""
parts = relative_path.replace("\\", "/").split("/")
if len(parts) >= 3:
try:
# Validate it's a real date
datetime.strptime(f"{parts[0]}-{parts[1]}-{parts[2]}", "%Y-%m-%d")
return f"{parts[0]}-{parts[1]}-{parts[2]}"
except ValueError:
pass
return None
# ---------------------------------------------------------------------------
# Asterisk spool
# ---------------------------------------------------------------------------
def spool_asterisk_set(
uniqueid: str,
tmp_dir: Path,
*,
call_date: str | None = None,
direction: str = CallDirection.UNKNOWN,
duration_s: int | None = None,
caller_phone: str | None = None,
user_id: str | None = None,
entity_type: str | None = None,
entity_id: str | None = None,
crm_links: dict | None = None,
external_call_id: str | None = None,
asterisk_meta: dict | None = None,
bitrix24_enrichment: dict | None = None,
) -> Path:
"""Atomically move a downloaded WAV set from *tmp_dir* into the spool.
Args:
call_date: Date of the call as "YYYY-MM-DD".
asterisk_meta: Parsed filename fields (from filename_parser).
bitrix24_enrichment: CRM enrichment data (from bitrix_enrichment).
*tmp_dir* must already contain mixed.wav, rx.wav, tx.wav.
Returns the final spool directory path.
"""
cfg = get_config()
date_str = call_date or datetime.now(UTC).strftime("%Y-%m-%d")
spool_dir = cfg.storage.spool_root / date_str / uniqueid
canonical_direction = canonicalize_direction(direction)
if spool_dir.exists():
log.warning(
"Spool dir already exists; skipping", uniqueid=uniqueid, path=str(spool_dir)
)
return spool_dir
# Validate all 3 WAVs are present in tmp_dir
for name in ("mixed.wav", "rx.wav", "tx.wav"):
if not (tmp_dir / name).exists():
raise FileNotFoundError(f"Missing {name} in temp dir {tmp_dir}")
# Move temp dir into place — same filesystem, so os.rename is atomic
spool_dir.parent.mkdir(parents=True, exist_ok=True)
try:
os.rename(tmp_dir, spool_dir)
except OSError:
log.warning(
"Cross-device rename; falling back to shutil.move",
src=str(tmp_dir),
dst=str(spool_dir),
)
shutil.move(str(tmp_dir), str(spool_dir))
# Build meta.json with all available data
meta: dict = {
"uniqueid": uniqueid,
"source": CallSource.ASTERISK,
"has_rx_tx": True,
"direction": canonical_direction,
"channel_roles": channel_roles_for_direction(canonical_direction),
"duration_s": duration_s,
"caller_phone": caller_phone,
"user_id": user_id,
"entity_type": entity_type,
"entity_id": entity_id,
"external_call_id": external_call_id,
"fetched_at": datetime.now(UTC).isoformat(),
"status": CallStatus.SPOOLED,
"crm": crm_links
or {
"user_id": user_id,
"contact_id": None,
"lead_id": None,
"company_id": None,
"entity_type": entity_type,
"entity_id": entity_id,
},
}
# Add parsed Asterisk filename fields
if asterisk_meta:
meta["asterisk"] = asterisk_meta
# Add Bitrix24 enrichment (activity, CRM entity, company, user)
if bitrix24_enrichment:
meta["bitrix24"] = bitrix24_enrichment
# Write meta.json last (readiness signal)