tp_voice/CLAUDE.md

16 KiB
Raw Permalink Blame History

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 four-process Python service that ingests voice call recordings, analyses them with LLMs, builds management reports, and imports transcript notes back into Bitrix24 call activities.

collector  →  spool (local FS)  →  analyzer  →  artifacts  →  reporter + importer

The deployed services run 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 — management reports + analytics indexing
│   │   ├── __init__.py
│   │   ├── 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
│   ├── importer/                 # Process 4 — Bitrix24 timeline note import
│   │   ├── __init__.py
│   │   └── main.py
│   ├── 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-analyzer.timer
│   ├── 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 collector/analyzer coupling point. After analysis, analyzer artifacts are the primary downstream contract for reporter and importer. Do not break these contracts without updating all dependent 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

{
  "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 (10-second cadence during 09:00-21:00 local time)

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 timer; each run processes the current spool backlog once.

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:

{
  "CALL_ID": "1701234567.42",
  "MESSAGES": [
    {
      "SIDE": "User",          // "User" | "Client"
      "START_TIME": 0,
      "STOP_TIME": 4,
      "MESSAGE": "Добрый день, компания Ромашка."
    }
  ],
  "artifact_kind": "transcript"
}

Emotion labels: neutral, positive, negative, angry, fearful, surprised, sad

Script compliance artifact format

{UNIQUEID}/script_analysis.json:

{
  "script_id":   "inbound_v3",
  "score":       74,           // 0–100
  "summary":     "...",
  "artifact_kind": "script_analysis",
  "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.

Downstream contract

  • conversation.json must include artifact_context; this file is the canonical downstream contract for identity and linkage fields.
  • artifact_context is the primary source for downstream identity and linkage fields: crm_activity_id, crm_entity_type, crm_entity_type_id, crm_entity_id, user_id, caller_phone, external call IDs, and voice_files.
  • Reporter and importer may use DB rows or meta.json only for lifecycle bookkeeping and legacy fallback.

Process 3 — Reporter

Entry point: reporter/main.py Run model: systemd service (long-running); polls for status=analyzed.

Reports and analytics

  • Reporter indexes analyzer artifacts into the analytics tables.
  • Reporter generates management-facing outputs only:
    • report_detail.html
    • summary reports
  • Reporter uses analyzer artifacts as the primary input contract.
  • Reporter does not deliver transcripts into Bitrix24 activities.

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.

Process 4 — Importer

Entry point: importer/main.py Run model: long-running process; polls for calls with completed analyzer output, importer_status eligible for retry, and no saved Bitrix24 note id.

Bitrix24 transcript note import

  • Uses crm.timeline.note.save against the existing call activity.
  • Request payload:
    • ownerTypeId = artifact_context.crm_entity_type_id
    • ownerId = artifact_context.crm_entity_id
    • itemType = 2
    • itemId = artifact_context.crm_activity_id
    • text = transcript note
  • Transcript note format is exact plain text:
    • MM:SS user: ...
    • MM:SS client: ...
  • Speaker mapping:
    • analyzer agent → user
    • analyzer customer → client
  • Importer is idempotent:
    • skip when bitrix_note_id already exists
    • store importer_status, imported_at, bitrix_note_id, and import_error independently from reporter_status
  • Importer writes bitrix_note.json as a local audit artifact next to analyzer outputs.

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:

[storage]
spool_root = "/var/lib/voice-pipeline/spool"
db_url     = "sqlite:////var/lib/voice-pipeline/db.sqlite3"

[schedule]
collect_interval = "10s"    # legacy override; deployed timer is hardcoded to 10s

[[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"

[importer]
enabled = true
# optional: poll_interval_s, retry_attempts, note_max_chars

Development setup

# 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
voice-pipeline importer

# Validate config and connectivity
voice-pipeline validate-config

# Run tests (pythonpath = ["src"] set in pyproject.toml)
pytest tests/ -v

Systemd deployment

# 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.timer
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.