1) Обновил документацию

2) Теперь artifact_context вставляется только в conversation.json. Из transcript.json, emotion.json и script_analysis.json он убран, чтобы не дублировать одни и те же данные в нескольких артефактах.
This commit is contained in:
Ilgiz Kalmetyev 2026-07-11 11:02:08 +05:00
parent 3689baf7a6
commit cb8e886bee
19 changed files with 973 additions and 154 deletions

188
CLAUDE.md
View File

@ -7,16 +7,16 @@ 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.
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 → 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`).
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`).
---
@ -38,16 +38,18 @@ voice-pipeline/
│ │ ├── 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
│ ├── 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
@ -62,8 +64,8 @@ voice-pipeline/
│ ├── 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
│ ├── voice-reporter.service # Uses: voice-pipeline reporter
│ └── install.sh
├── config/
│ └── config.example.toml # Fully commented reference config
├── scripts/
@ -84,8 +86,9 @@ voice-pipeline/
## 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.
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
@ -175,35 +178,38 @@ This is the core correctness requirement — **do not change without updating bo
| `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`:
### 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`
{
"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}/analysis.json`:
`{UNIQUEID}/script_analysis.json`:
```jsonc
{
"script_id": "inbound_v3",
"score": 74, // 0–100
"summary": "...",
"checklist": [
{
"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 }
]
@ -216,23 +222,31 @@ Emotion labels: `neutral`, `positive`, `negative`, `angry`, `fearful`, `surprise
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`.
- 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
@ -240,7 +254,34 @@ Emotion labels: `neutral`, `positive`, `negative`, `angry`, `fearful`, `surprise
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.
- 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 analyzed/reported calls with analyzer artifacts 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 `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.
---
@ -264,8 +305,8 @@ transport = "sftp" # "sftp" | "http"
host = "pbx.example.com"
# ... credentials, path, filename_pattern
[sources.bitrix24]
webhook_url = "https://portal.bitrix24.ru/rest/1/xxxx/"
[sources.bitrix24]
webhook_url = "https://portal.bitrix24.ru/rest/1/xxxx/"
[llm]
backend = "cloud" # "cloud" | "local"
@ -273,10 +314,14 @@ 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"
[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
```
---
@ -302,9 +347,10 @@ 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 collector
voice-pipeline analyzer
voice-pipeline reporter
voice-pipeline importer
# Validate config and connectivity
voice-pipeline validate-config

View File

@ -1,16 +1,15 @@
# voice-pipeline
`voice-pipeline` is a three-process Python service for collecting call recordings, analyzing them, and generating local reports.
`voice-pipeline` is a four-process Python service for collecting call recordings, analyzing them, generating local reports, and importing call transcripts back into Bitrix24.
## What it does
- `collector` fetches call metadata and recordings from Bitrix24 / Asterisk sources and writes them into a local spool directory.
- `analyzer` picks up spooled calls, transcribes them, performs diarization and script compliance checks, and stores artifacts under a dedicated analyzer artifacts root.
- `reporter` creates HTML reports from analyzed calls and stores them under `reports_root`.
- `reporter` also indexes analyzer artifacts into a normalized analytics store and
builds summary/detail views from that store.
- `reporter` creates HTML reports from analyzed calls, stores them under `reports_root`, and builds management detail/summary views from analyzer artifacts.
- `importer` reads analyzer artifacts and writes transcript notes into existing Bitrix24 call activities via `crm.timeline.note.save`.
The processes communicate through the spool directory and the shared `meta.json` contract stored inside each call folder.
The processes communicate through the spool directory and the shared `meta.json` contract stored inside each call folder. After analysis, downstream modules use analyzer artifacts as the primary business contract; DB rows and `meta.json` remain lifecycle and legacy-fallback storage.
## Requirements
@ -115,6 +114,7 @@ Important sections:
`provider = "openrouter"` with `interface = "openai"` is valid, as are local runtimes like
`provider = "local-faster-whisper"` with `interface = "faster_whisper"`.
- `[reporter]` controls report size and summary window.
- `[importer]` controls Bitrix24 transcript-note import behavior.
Run a validation check after editing the config:
@ -131,6 +131,7 @@ voice-pipeline validate-config
voice-pipeline collector
voice-pipeline analyzer
voice-pipeline reporter
voice-pipeline importer
voice-pipeline reload --list --date 2026-06-23
voice-pipeline reload --reanalyze --uniqueid 1782211489.118028
voice-pipeline reload --recollect --status failed
@ -159,18 +160,48 @@ The collector currently uses `voximplant.statistic.get` as the main source of tr
- `Asterisk` calls are resolved in the Asterisk storage by `EXTERNAL_CALL_ID`.
- Partial Asterisk matches can be spooled when only some of `mixed/rx/tx` are present.
Each spooled call gets a `meta.json` file with the structured metadata used by the analyzer and reporter.
Each spooled call gets a `meta.json` file with the structured metadata used by the analyzer and for legacy fallback in downstream modules.
## Analyzer behavior
- Asterisk split-channel calls use `rx.wav` and `tx.wav`.
- Mixed audio calls use `audio.mp3` or fallback `mixed.wav` when available.
- Analyzer artifacts are written under `storage.analyzer_artifacts_root/{date}/{uniqueid}`.
- `conversation.json` includes the canonical `artifact_context` block. Downstream modules rely on it as the primary source for:
`crm_activity_id`, `crm_entity_type`, `crm_entity_type_id`, `crm_entity_id`, `user_id`,
`caller_phone`, call linkage IDs, and `voice_files`.
- Cloud gateways that expose OpenAI-compatible APIs can be configured with
`interface = "openai"` plus a custom `base_url`.
- Groq-compatible gateways can be configured the same way with
`interface = "groq"` plus an optional `base_url`.
## Reporter behavior
- `reporter` uses analyzer artifacts as the primary reporting input.
- It indexes transcript, conversation, emotion, and script-analysis artifacts into the analytics store.
- It generates:
- per-call `report_detail.html`
- daily / windowed management summary reports
- `reporter` does not create Bitrix24 call activities for transcript delivery.
## Importer behavior
- `importer` is a standalone process that does not change the main call lifecycle owned by `reporter`.
- It only processes calls that already have analyzer artifacts and no saved Bitrix24 note id.
- It reads `artifact_context` and writes a note into the existing Bitrix24 call activity using:
- `ownerTypeId = crm_entity_type_id`
- `ownerId = crm_entity_id`
- `itemType = 2`
- `itemId = crm_activity_id`
- The note text format is:
```text
MM:SS user: ...
MM:SS client: ...
```
- On success it stores importer markers in the DB and writes a local audit artifact `bitrix_note.json` next to the analyzer artifacts.
## Systemd deployment
The repository includes unit files and an installer script:
@ -202,6 +233,7 @@ pytest tests/test_integration.py -q
- `src/analyzer/` - transcription, diarization, emotion scoring, script checks
- `src/reporter/` - HTML report generation and analytics snapshots
- `src/reporter/api.py` - query helpers for call list/detail/snapshots
- `src/importer/` - Bitrix24 transcript-note import process
- `src/core/` - shared config, database, models, logging, retries
- `systemd/` - service units and install script
- `config/` - example configuration

View File

@ -48,8 +48,8 @@ level = "INFO"
# Examples: "5min", "15min", "1h"
collect_interval = "5min"
# Poll interval in seconds for the analyzer and reporter long-running services.
poll_interval_s = 10
# Poll interval in seconds for the analyzer, reporter, and importer long-running services.
poll_interval_s = 10
# ---------------------------------------------------------------------------
@ -208,9 +208,26 @@ device_preference = "auto"
# ---------------------------------------------------------------------------
# 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
[reporter]
# Maximum characters for transcript excerpts rendered in reporter-managed outputs.
bitrix_description_max_chars = 10000
# Days covered by each batch summary report.
summary_window_days = 1
# ---------------------------------------------------------------------------
# Importer
# ---------------------------------------------------------------------------
[importer]
# Enable Bitrix24 timeline note import for analyzed calls.
enabled = true
# Optional override; when omitted, schedule.poll_interval_s is used.
# poll_interval_s = 10
# Optional override; when omitted, sources.bitrix24.retry_attempts is used.
# retry_attempts = 3
# Optional maximum note length before truncation; omit to send full transcript.
# note_max_chars = 10000

View File

@ -40,7 +40,7 @@ voice-pipeline reload --reanalyze --status failed
voice-pipeline reload --reanalyze --date 2026-06-23
```
Что делает: `status→spooled`, `failure_count→0`, чистит `last_error`, обновляет `meta.json`. Analyzer подхватит при следующем поллинге.
Что делает: `status→spooled`, `failure_count→0`, чистит `last_error`, обновляет `meta.json`, а также сбрасывает маркеры downstream-обработки `reported_at`, `imported_at`, `bitrix_note_id`, `import_error`. Analyzer подхватит при следующем поллинге.
---

View File

@ -75,7 +75,7 @@ voice-pipeline = "voice_pipeline.__main__:main"
[tool.setuptools.packages.find]
where = ["src"]
include = ["voice_pipeline*", "collector*", "analyzer*", "reporter*", "core*"]
include = ["voice_pipeline*", "collector*", "analyzer*", "reporter*", "importer*", "core*"]
[tool.ruff]
line-length = 100

View File

@ -12,7 +12,7 @@ from typing import Any, cast
from sqlmodel import select
from analyzer.provider_manager import NoProviderAvailable, reset_provider_manager
from analyzer.transcript_format import build_artifact_context, build_bitrix_transcript_payload
from analyzer.transcript_format import build_bitrix_transcript_payload
from collector.spooler import read_meta, update_meta_status
from core.config import load_config
from core.db import get_session, init_db
@ -113,11 +113,8 @@ def _build_emotion_artifact(turns: list[dict[str, Any]]) -> dict[str, Any]:
}
def _with_artifact_context(
payload: dict[str, Any], meta: dict[str, Any], artifact_kind: str
) -> dict[str, Any]:
def _with_artifact_kind(payload: dict[str, Any], artifact_kind: str) -> dict[str, Any]:
enriched = dict(payload)
enriched["artifact_context"] = build_artifact_context(meta)
enriched["artifact_kind"] = artifact_kind
return enriched
@ -235,7 +232,7 @@ def process_call(
emotion_path = record.emotion_path
_write_json_artifact(
emotion_path,
_with_artifact_context(_build_emotion_artifact(turns), meta, "emotion"),
_with_artifact_kind(_build_emotion_artifact(turns), "emotion"),
)
log.info(
"Step 4/5: analyzer artifacts written", uniqueid=uid, segments=len(turns)
@ -253,9 +250,7 @@ def process_call(
analysis_path = record.analysis_path
_write_json_artifact(
analysis_path,
_with_artifact_context(
analysis_to_dict(analysis_result), meta, "script_analysis"
),
_with_artifact_kind(analysis_to_dict(analysis_result), "script_analysis"),
)
log.info(
"Step 5/5: script compliance DONE",

View File

@ -13,6 +13,13 @@ _SPEAKER_TO_SIDE = {
"customer": "Client",
}
_CRM_ENTITY_TYPE_IDS = {
"LEAD": 1,
"DEAL": 2,
"CONTACT": 3,
"COMPANY": 4,
}
def _first_non_empty(*values: Any) -> str | None:
for value in values:
@ -136,6 +143,39 @@ def _recording_source_identifiers(meta: dict[str, Any]) -> dict[str, str | None]
}
def _crm_entity_type_id(meta: dict[str, Any]) -> int | None:
candidates = [
meta.get("crm_entity_type_id"),
meta.get("CRM_ENTITY_TYPE_ID"),
meta.get("entity_type_id"),
]
voximplant = meta.get("voximplant")
if isinstance(voximplant, dict):
candidates.extend(
[
voximplant.get("CRM_ENTITY_TYPE_ID"),
voximplant.get("crm_entity_type_id"),
voximplant.get("OWNER_TYPE_ID"),
]
)
for value in candidates:
try:
if value not in (None, ""):
return int(value)
except (TypeError, ValueError):
continue
entity_type = _first_non_empty(
meta.get("entity_type"),
meta.get("CRM_ENTITY_TYPE"),
isinstance(voximplant, dict) and voximplant.get("CRM_ENTITY_TYPE"),
)
if entity_type is None:
return None
return _CRM_ENTITY_TYPE_IDS.get(entity_type.upper())
def _participant_from_role(role: str, meta: dict[str, Any]) -> dict[str, Any]:
if role == "agent":
first_name, last_name = _user_names(meta)
@ -361,6 +401,7 @@ def build_artifact_context(meta: dict[str, Any]) -> dict[str, Any]:
meta.get("CRM_ENTITY_TYPE"),
voximplant.get("CRM_ENTITY_TYPE"),
),
"crm_entity_type_id": _crm_entity_type_id(meta),
"crm_entity_id": _first_non_empty(
meta.get("entity_id"),
meta.get("CRM_ENTITY_ID"),
@ -381,6 +422,7 @@ def build_artifact_context(meta: dict[str, Any]) -> dict[str, Any]:
voximplant.get("CRM_ENTITY_TYPE"),
meta.get("entity_type"),
),
"CRM_ENTITY_TYPE_ID": _crm_entity_type_id(meta),
"CRM_ENTITY_ID": _first_non_empty(
meta.get("CRM_ENTITY_ID"),
voximplant.get("CRM_ENTITY_ID"),
@ -469,5 +511,4 @@ def build_bitrix_transcript_payload(
"CALL_ID": call_id_from_meta(meta),
"MESSAGES": messages,
"artifact_kind": "transcript",
"artifact_context": build_artifact_context(meta),
}

View File

@ -149,10 +149,36 @@ class Bitrix24Client:
result = self.call("crm.activity.list", params)
return result if isinstance(result, list) else []
def activity_add(self, fields: dict[str, Any]) -> str:
"""Create a CRM activity and return its ID as a string."""
result = self.call("crm.activity.add", {"fields": fields})
return str(result)
def activity_add(self, fields: dict[str, Any]) -> str:
"""Create a CRM activity and return its ID as a string."""
result = self.call("crm.activity.add", {"fields": fields})
return str(result)
def timeline_note_save(
self,
*,
owner_type_id: int,
owner_id: str,
item_type: int,
item_id: str,
text_value: str,
) -> str:
"""Create a CRM timeline note and return its ID as a string."""
result = self.call(
"crm.timeline.note.save",
{
"ownerTypeId": owner_type_id,
"ownerId": int(owner_id),
"itemType": item_type,
"itemId": int(item_id),
"text": text_value,
},
)
if isinstance(result, dict):
note_id = result.get("id", result.get("ID"))
if note_id not in (None, ""):
return str(note_id)
return str(result)
def get_contact_by_phone(self, phone: str) -> dict[str, Any] | None:
results = self.call(

View File

@ -257,6 +257,13 @@ class ReporterConfig(BaseModel):
summary_window_days: int = 1
class ImporterConfig(BaseModel):
enabled: bool = True
poll_interval_s: int | None = None
retry_attempts: int | None = None
note_max_chars: int | None = None
class LoggingConfig(BaseModel):
level: Literal["DEBUG", "INFO", "WARN", "ERROR", "FATAL"] = "INFO"
@ -281,6 +288,7 @@ class Config(BaseModel):
llm: LLMConfig = Field(default_factory=LLMConfig)
analyzer: AnalyzerConfig = Field(default_factory=AnalyzerConfig)
reporter: ReporterConfig = Field(default_factory=ReporterConfig)
importer: ImporterConfig = Field(default_factory=ImporterConfig)
logging: LoggingConfig = Field(default_factory=LoggingConfig)
@model_validator(mode="after")

View File

@ -1,9 +1,10 @@
from __future__ import annotations
from collections.abc import Generator
from contextlib import contextmanager
from sqlmodel import Session, SQLModel, create_engine
from collections.abc import Generator
from contextlib import contextmanager
from sqlalchemy import text
from sqlmodel import Session, SQLModel, create_engine
from core.config import get_config
from core.logger import get_logger
@ -29,11 +30,12 @@ def get_engine():
return _engine
def init_db() -> None:
"""Create all tables. Safe to call multiple times (CREATE IF NOT EXISTS)."""
engine = get_engine()
SQLModel.metadata.create_all(engine)
log.info("Database schema initialised")
def init_db() -> None:
"""Create all tables. Safe to call multiple times (CREATE IF NOT EXISTS)."""
engine = get_engine()
SQLModel.metadata.create_all(engine)
_ensure_call_record_columns(engine)
log.info("Database schema initialised")
@contextmanager
@ -46,4 +48,25 @@ def get_session() -> Generator[Session, None, None]:
session.commit()
except Exception:
session.rollback()
raise
raise
def _ensure_call_record_columns(engine) -> None:
cfg = get_config()
if not cfg.storage.db_url.startswith("sqlite"):
return
required_columns = {
"imported_at": "DATETIME",
"bitrix_note_id": "VARCHAR",
"import_error": "VARCHAR",
}
with engine.begin() as conn:
rows = conn.execute(text("PRAGMA table_info(call_records)")).fetchall()
existing = {str(row[1]) for row in rows}
for name, ddl_type in required_columns.items():
if name in existing:
continue
conn.execute(
text(f"ALTER TABLE call_records ADD COLUMN {name} {ddl_type}")
)
log.info("Added missing call_records column", column=name)

View File

@ -77,12 +77,15 @@ class CallRecord(SQLModel, table=True): # type: ignore[call-arg, misc]
fetched_at: datetime = Field(default_factory=datetime.utcnow)
analyzed_at: datetime | None = None
reported_at: datetime | None = None
imported_at: datetime | None = None
status: str = CallStatus.SPOOLED
failure_count: int = 0
last_error: str | None = None
bitrix_activity_id: str | None = None
bitrix_note_id: str | None = None
import_error: str | None = None
@property
def spool_path(self) -> Path:
@ -156,6 +159,10 @@ class CallRecord(SQLModel, table=True): # type: ignore[call-arg, misc]
def analysis_path(self) -> Path:
return self.analyzer_artifact_dir / "script_analysis.json"
@property
def bitrix_note_path(self) -> Path:
return self.analyzer_artifact_dir / "bitrix_note.json"
@property
def report_detail_path(self) -> Path:
return self.report_artifact_dir / "report_detail.html"

2
src/importer/__init__.py Normal file
View File

@ -0,0 +1,2 @@
from __future__ import annotations

286
src/importer/main.py Normal file
View File

@ -0,0 +1,286 @@
from __future__ import annotations
import json
import os
import time
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, cast
from sqlmodel import select
from core.bitrix_client import Bitrix24Client
from core.config import load_config
from core.db import get_session, init_db
from core.logger import configure_logging, get_logger
from core.models import AnalysisArtifact, CallRecord, CallStatus
log = get_logger(__name__)
def _safe_json_load(path: Path) -> dict[str, Any] | list[Any] | None:
if not path.exists():
return None
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return None
def _write_json_artifact(path: Path, data: object) -> None:
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
os.rename(tmp, path)
def _artifact_context(record: CallRecord) -> dict[str, Any]:
for path in (record.transcript_path, record.conversation_path, record.analysis_path):
payload = _safe_json_load(path)
if isinstance(payload, dict):
context = payload.get("artifact_context")
if isinstance(context, dict):
return context
payload = _safe_json_load(record.meta_path)
meta = payload if isinstance(payload, dict) else {}
voximplant = meta.get("voximplant") if isinstance(meta.get("voximplant"), dict) else {}
return {
"crm_activity_id": meta.get("crm_activity_id")
or meta.get("CRM_ACTIVITY_ID")
or voximplant.get("CRM_ACTIVITY_ID"),
"crm_entity_type": meta.get("entity_type")
or meta.get("CRM_ENTITY_TYPE")
or voximplant.get("CRM_ENTITY_TYPE"),
"crm_entity_type_id": meta.get("crm_entity_type_id")
or meta.get("CRM_ENTITY_TYPE_ID")
or voximplant.get("CRM_ENTITY_TYPE_ID"),
"crm_entity_id": meta.get("entity_id")
or meta.get("CRM_ENTITY_ID")
or voximplant.get("CRM_ENTITY_ID"),
}
def _load_transcript_messages(record: CallRecord) -> list[dict[str, Any]]:
payload = _safe_json_load(record.transcript_path)
if not isinstance(payload, dict):
return []
messages = payload.get("MESSAGES")
return messages if isinstance(messages, list) else []
def _speaker_label(side: str) -> str:
return "client" if side.casefold() == "client" else "user"
def _format_timestamp(seconds_value: Any) -> str:
try:
total_seconds = int(float(seconds_value or 0))
except (TypeError, ValueError):
total_seconds = 0
minutes, seconds = divmod(total_seconds, 60)
return f"{minutes:02d}:{seconds:02d}"
def format_note_text(record: CallRecord, max_chars: int | None = None) -> str:
lines: list[str] = []
for item in _load_transcript_messages(record):
if not isinstance(item, dict):
continue
text = str(item.get("MESSAGE", "")).strip()
if not text:
continue
timestamp = _format_timestamp(item.get("START_TIME", 0))
speaker = _speaker_label(str(item.get("SIDE", "User")))
lines.append(f"{timestamp} {speaker}: {text}")
full = "\n".join(lines)
if max_chars is None or len(full) <= max_chars:
return full
return full[:max_chars].rstrip()
def _validate_context(record: CallRecord) -> tuple[dict[str, Any], list[str]]:
context = _artifact_context(record)
missing: list[str] = []
for key in ("crm_activity_id", "crm_entity_id", "crm_entity_type_id"):
if context.get(key) in (None, "", []):
missing.append(key)
return context, missing
def _build_note_payload(record: CallRecord, max_chars: int | None = None) -> dict[str, Any]:
if not record.transcript_path.exists():
raise RuntimeError("Transcript artifact is missing")
context, missing = _validate_context(record)
if missing:
raise RuntimeError(
"Missing Bitrix linkage in analyzer artifacts: " + ", ".join(missing)
)
note_text = format_note_text(record, max_chars=max_chars)
if not note_text:
raise RuntimeError("Transcript note text is empty")
return {
"ownerTypeId": int(context["crm_entity_type_id"]),
"ownerId": int(str(context["crm_entity_id"])),
"itemType": 2,
"itemId": int(str(context["crm_activity_id"])),
"text": note_text,
}
def _register_artifact(
session,
call_record_id: int,
uniqueid: str,
artifact_type: str,
file_path: Path,
) -> None:
existing = session.exec(
select(AnalysisArtifact).where(
AnalysisArtifact.call_record_id == call_record_id,
AnalysisArtifact.artifact_type == artifact_type,
)
).all()
for art in existing:
session.delete(art)
session.add(
AnalysisArtifact(
call_record_id=call_record_id,
uniqueid=uniqueid,
artifact_type=artifact_type,
file_path=str(file_path),
size_bytes=file_path.stat().st_size if file_path.exists() else None,
)
)
def _write_audit_artifact(
record: CallRecord,
*,
payload: dict[str, Any],
note_id: str | None,
error: str | None,
) -> None:
audit = {
"saved_at": datetime.now(UTC).isoformat(),
"uniqueid": record.uniqueid,
"payload": payload,
"bitrix_note_id": note_id,
"error": error,
}
path = record.bitrix_note_path
path.parent.mkdir(parents=True, exist_ok=True)
_write_json_artifact(path, audit)
if record.id is None:
return
with get_session() as session:
_register_artifact(session, record.id, record.uniqueid, "bitrix_note", path)
def import_call(record: CallRecord | None) -> None:
if record is None:
raise RuntimeError("CallRecord is required")
if record.bitrix_note_id:
log.info("Skipping already imported call", uniqueid=record.uniqueid)
return
cfg = load_config()
b24_cfg = cfg.sources.bitrix24
if b24_cfg is None:
raise RuntimeError("sources.bitrix24 not configured - cannot import note")
client = Bitrix24Client(
webhook_url=b24_cfg.webhook_url,
retry_attempts=cfg.importer.retry_attempts or b24_cfg.retry_attempts,
retry_backoff_s=b24_cfg.retry_backoff_s,
)
try:
payload = _build_note_payload(record, max_chars=cfg.importer.note_max_chars)
log.info("Importing Bitrix24 timeline note", uniqueid=record.uniqueid)
note_id = client.timeline_note_save(
owner_type_id=payload["ownerTypeId"],
owner_id=str(payload["ownerId"]),
item_type=payload["itemType"],
item_id=str(payload["itemId"]),
text_value=str(payload["text"]),
)
except Exception as exc:
error = str(exc)[:2000]
payload = locals().get("payload") or {}
_write_audit_artifact(
record,
payload=cast(dict[str, Any], payload),
note_id=None,
error=error,
)
with get_session() as session:
rec = session.get(CallRecord, record.id)
if rec is None:
raise RuntimeError(f"CallRecord {record.uniqueid!r} disappeared")
rec.import_error = error
raise
_write_audit_artifact(record, payload=payload, note_id=note_id, error=None)
with get_session() as session:
rec = session.get(CallRecord, record.id)
if rec is None:
raise RuntimeError(f"CallRecord {record.uniqueid!r} disappeared")
rec.bitrix_note_id = note_id
rec.imported_at = datetime.now(UTC)
rec.import_error = None
def main() -> None:
cfg = load_config()
configure_logging(level=cfg.logging.level)
init_db()
if not cfg.importer.enabled:
log.info("Importer disabled by config")
return
poll_interval_s = cfg.importer.poll_interval_s or cfg.schedule.poll_interval_s
log.info("Importer service starting", poll_interval_s=poll_interval_s)
from core.daemon import GracefulExit
stop = GracefulExit()
while not stop.requested:
with get_session() as session:
pending = list(
session.exec(
select(CallRecord)
.where(
CallRecord.imported_at.is_(None),
CallRecord.bitrix_note_id.is_(None),
cast(Any, CallRecord.status).in_(
[CallStatus.ANALYZED, CallStatus.REPORTED]
),
)
.order_by(cast(Any, CallRecord.analyzed_at), cast(Any, CallRecord.reported_at))
.limit(10)
).all()
)
pending = [record for record in pending if record.transcript_path.exists()]
if not pending:
log.debug("No importer targets; sleeping", seconds=poll_interval_s)
time.sleep(poll_interval_s)
continue
for record in pending:
if stop.requested:
break
try:
import_call(record)
except Exception as exc:
log.exception(
"Importer failed for call",
uniqueid=record.uniqueid,
error=str(exc),
)

View File

@ -677,62 +677,69 @@ def _normalize_identity(
"ingestion_status": IngestionStatus.NEW,
"match_method": "exact",
"match_score": 1.0,
"external_call_id": _get_first(
meta, ["external_call_id", "EXTERNAL_CALL_ID", "CALL_ID"]
)
or _get_first_nested(
"external_call_id": _get_first_nested(
artifact_context,
[
("external_call_id",),
("bitrix_fields", "EXTERNAL_CALL_ID"),
("bitrix_fields", "CALL_ID"),
],
),
"voximplant_call_id": _get_first(
meta, ["voximplant_call_id", "CALL_ID", "EXTERNAL_CALL_ID"]
)
or _get_first_nested(
or _get_first(
meta, ["external_call_id", "EXTERNAL_CALL_ID", "CALL_ID"]
),
"voximplant_call_id": _get_first_nested(
artifact_context,
[
("voximplant_call_id",),
("bitrix_fields", "CALL_ID"),
("bitrix_fields", "EXTERNAL_CALL_ID"),
],
)
or _get_first(
meta, ["voximplant_call_id", "CALL_ID", "EXTERNAL_CALL_ID"]
),
"crm_activity_id": _get_first(meta, ["crm_activity_id", "CRM_ACTIVITY_ID"])
or _get_first_nested(
"crm_activity_id": _get_first_nested(
artifact_context,
[
("crm_activity_id",),
("bitrix_fields", "CRM_ACTIVITY_ID"),
],
),
"employee_user_id": record.user_id,
"entity_type": record.entity_type
or _get_first_nested(
)
or _get_first(meta, ["crm_activity_id", "CRM_ACTIVITY_ID"]),
"employee_user_id": _get_first_nested(
artifact_context,
[
("user_id",),
("bitrix_fields", "PORTAL_USER_ID"),
],
)
or record.user_id,
"entity_type": _get_first_nested(
artifact_context,
[
("crm_entity_type",),
("bitrix_fields", "CRM_ENTITY_TYPE"),
],
),
"entity_id": record.entity_id
or _get_first_nested(
)
or record.entity_type,
"entity_id": _get_first_nested(
artifact_context,
[
("crm_entity_id",),
("bitrix_fields", "CRM_ENTITY_ID"),
],
),
"caller_phone": record.caller_phone
or _get_first(meta, ["caller_phone", "PHONE", "caller"])
or _get_first_nested(
)
or record.entity_id,
"caller_phone": _get_first_nested(
artifact_context,
[
("caller_phone",),
("bitrix_fields", "PHONE_NUMBER"),
],
),
)
or record.caller_phone
or _get_first(meta, ["caller_phone", "PHONE", "caller"]),
"canonical_uniqueid": record.uniqueid,
"identity_json": _safe_json_dump(
{

View File

@ -2,13 +2,14 @@ from __future__ import annotations
"""voice_pipeline.__main__ — CLI entry point.
Usage:
voice-pipeline validate-config
voice-pipeline collector
voice-pipeline analyzer
voice-pipeline reporter
voice-pipeline reload --reanalyze
[--uniqueid UID | --date YYYY-MM-DD | --status failed|dead_letter]
Usage:
voice-pipeline validate-config
voice-pipeline collector
voice-pipeline analyzer
voice-pipeline reporter
voice-pipeline importer
voice-pipeline reload --reanalyze
[--uniqueid UID | --date YYYY-MM-DD | --status failed|dead_letter]
voice-pipeline reload --recollect [--uniqueid UID | --date YYYY-MM-DD]
voice-pipeline reload --repair
[--uniqueid UID | --date YYYY-MM-DD | --from-date YYYY-MM-DD | --status STATUS]
@ -42,10 +43,15 @@ def main() -> None:
run()
case "reporter":
from reporter.main import main as run
run()
case "reporter":
from reporter.main import main as run
run()
case "importer":
from importer.main import main as run
run()
case "reload":
_reload(args[1:])
@ -238,10 +244,13 @@ def _do_reanalyze(records) -> None:
raise RuntimeError(f"CallRecord {rec.uniqueid!r} disappeared")
db_rec.status = CallStatus.SPOOLED
db_rec.failure_count = 0
db_rec.last_error = None
db_rec.analyzed_at = None
db_rec.reported_at = None
db_rec.bitrix_activity_id = None
db_rec.last_error = None
db_rec.analyzed_at = None
db_rec.reported_at = None
db_rec.imported_at = None
db_rec.bitrix_activity_id = None
db_rec.bitrix_note_id = None
db_rec.import_error = None
# Update meta.json
meta_path = spool_dir / "meta.json"

View File

@ -64,3 +64,33 @@ def test_call_retries_and_raises_http_error_for_generic_http_failure(monkeypatch
client.call("crm.lead.get", {"ID": "404"})
assert sleeps == [2.0, 4.0]
def test_timeline_note_save_calls_expected_method(monkeypatch):
client = Bitrix24Client("https://example.test/rest/1/token/")
captured: dict[str, object] = {}
def _fake_call(method: str, params: dict[str, object] | None = None):
captured["method"] = method
captured["params"] = params or {}
return {"id": 321}
monkeypatch.setattr(client, "call", _fake_call)
note_id = client.timeline_note_save(
owner_type_id=4,
owner_id="218369",
item_type=2,
item_id="1047230",
text_value="00:03 user: hello",
)
assert note_id == "321"
assert captured["method"] == "crm.timeline.note.save"
assert captured["params"] == {
"ownerTypeId": 4,
"ownerId": 218369,
"itemType": 2,
"itemId": 1047230,
"text": "00:03 user: hello",
}

254
tests/test_importer.py Normal file
View File

@ -0,0 +1,254 @@
from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
import pytest
from sqlmodel import select
@pytest.fixture(autouse=True)
def reset_config_singleton():
from core.config import reset_config
reset_config()
yield
reset_config()
@dataclass
class ImporterEnv:
spool: Path
artifacts: Path
db_path: Path
@pytest.fixture()
def importer_env(tmp_path: Path) -> ImporterEnv:
from core.config import load_config
from core.db import init_db
spool = tmp_path / "spool"
artifacts = tmp_path / "artifacts"
reports = tmp_path / "reports"
db_path = tmp_path / "test.db"
config_path = tmp_path / "config.toml"
spool.mkdir()
artifacts.mkdir()
reports.mkdir()
config_path.write_text(
f"""
[storage]
spool_root = "{spool}"
reports_root = "{reports}"
analyzer_artifacts_root = "{artifacts}"
runtime_state_root = "{tmp_path / "state"}"
db_url = "sqlite:///{db_path}"
[schedule]
poll_interval_s = 1
[sources.bitrix24]
webhook_url = "https://example.test/rest/1/token/"
retry_attempts = 3
retry_backoff_s = 2.0
[importer]
enabled = true
""",
encoding="utf-8",
)
load_config(config_path)
init_db()
return ImporterEnv(spool=spool, artifacts=artifacts, db_path=db_path)
def _create_record(importer_env: ImporterEnv, uniqueid: str = "uid-1"):
from core.db import get_session
from core.models import CallRecord, CallStatus
spool_dir = importer_env.spool / "2026-07-11" / uniqueid
spool_dir.mkdir(parents=True, exist_ok=True)
(spool_dir / "meta.json").write_text("{}", encoding="utf-8")
with get_session() as session:
record = CallRecord(
uniqueid=uniqueid,
source="bitrix24",
direction="inbound",
spool_dir=str(spool_dir),
status=CallStatus.ANALYZED,
)
session.add(record)
with get_session() as session:
return session.exec(
select(CallRecord).where(CallRecord.uniqueid == uniqueid)
).first()
def _write_transcript(record, payload: dict[str, object]) -> None:
record.transcript_path.parent.mkdir(parents=True, exist_ok=True)
record.transcript_path.write_text(
json.dumps(payload, ensure_ascii=False, indent=2),
encoding="utf-8",
)
def test_format_note_text_uses_user_client_and_skips_empty(importer_env: ImporterEnv):
from importer.main import format_note_text
record = _create_record(importer_env, uniqueid="fmt-1")
_write_transcript(
record,
{
"CALL_ID": "call-1",
"artifact_context": {
"crm_activity_id": "77",
"crm_entity_type_id": 4,
"crm_entity_id": "55",
},
"MESSAGES": [
{"SIDE": "User", "START_TIME": 3, "STOP_TIME": 7, "MESSAGE": "Добрый день"},
{"SIDE": "Client", "START_TIME": 11, "STOP_TIME": 16, "MESSAGE": "Да"},
{"SIDE": "User", "START_TIME": 16, "STOP_TIME": 18, "MESSAGE": " "},
],
},
)
assert (
format_note_text(record)
== "00:03 user: Добрый день\n00:11 client: Да"
)
def test_import_call_persists_note_id_and_audit(monkeypatch, importer_env: ImporterEnv):
from core.db import get_session
from core.models import AnalysisArtifact, CallRecord
from importer.main import import_call
record = _create_record(importer_env, uniqueid="imp-1")
_write_transcript(
record,
{
"CALL_ID": "call-1",
"artifact_context": {
"crm_activity_id": "1047230",
"crm_entity_type": "COMPANY",
"crm_entity_type_id": 4,
"crm_entity_id": "218369",
},
"MESSAGES": [
{"SIDE": "User", "START_TIME": 3, "STOP_TIME": 7, "MESSAGE": "Добрый день"},
{"SIDE": "Client", "START_TIME": 11, "STOP_TIME": 16, "MESSAGE": "Да"},
],
},
)
captured: dict[str, object] = {}
def _fake_save(**kwargs):
captured.update(kwargs)
return "note-123"
monkeypatch.setattr(
"importer.main.Bitrix24Client.timeline_note_save",
lambda self, **kwargs: _fake_save(**kwargs),
)
import_call(record)
assert captured == {
"owner_type_id": 4,
"owner_id": "218369",
"item_type": 2,
"item_id": "1047230",
"text_value": "00:03 user: Добрый день\n00:11 client: Да",
}
with get_session() as session:
refreshed = session.exec(
select(CallRecord).where(CallRecord.uniqueid == "imp-1")
).first()
artifact = session.exec(
select(AnalysisArtifact).where(
AnalysisArtifact.uniqueid == "imp-1",
AnalysisArtifact.artifact_type == "bitrix_note",
)
).first()
assert refreshed is not None
assert refreshed.bitrix_note_id == "note-123"
assert refreshed.imported_at is not None
assert refreshed.import_error is None
assert artifact is not None
assert refreshed.bitrix_note_path.exists()
audit = json.loads(refreshed.bitrix_note_path.read_text(encoding="utf-8"))
assert audit["bitrix_note_id"] == "note-123"
assert audit["payload"]["ownerTypeId"] == 4
def test_import_call_records_error_for_missing_linkage(importer_env: ImporterEnv):
from core.db import get_session
from core.models import CallRecord
from importer.main import import_call
record = _create_record(importer_env, uniqueid="imp-err")
_write_transcript(
record,
{
"CALL_ID": "call-err",
"artifact_context": {
"crm_entity_type_id": 4,
"crm_entity_id": "218369",
},
"MESSAGES": [
{"SIDE": "User", "START_TIME": 3, "STOP_TIME": 7, "MESSAGE": "Добрый день"}
],
},
)
with pytest.raises(RuntimeError, match="crm_activity_id"):
import_call(record)
with get_session() as session:
refreshed = session.exec(
select(CallRecord).where(CallRecord.uniqueid == "imp-err")
).first()
assert refreshed is not None
assert refreshed.bitrix_note_id is None
assert refreshed.imported_at is None
assert "crm_activity_id" in str(refreshed.import_error)
assert refreshed.bitrix_note_path.exists()
def test_import_call_skips_existing_note(monkeypatch, importer_env: ImporterEnv):
from core.db import get_session
from core.models import CallRecord
from importer.main import import_call
record = _create_record(importer_env, uniqueid="imp-skip")
with get_session() as session:
refreshed = session.exec(
select(CallRecord).where(CallRecord.uniqueid == "imp-skip")
).first()
assert refreshed is not None
refreshed.bitrix_note_id = "note-existing"
called = {"value": False}
monkeypatch.setattr(
"importer.main.Bitrix24Client.timeline_note_save",
lambda self, **kwargs: called.__setitem__("value", True),
)
with get_session() as session:
record = session.exec(
select(CallRecord).where(CallRecord.uniqueid == "imp-skip")
).first()
import_call(record)
assert called["value"] is False

View File

@ -270,6 +270,43 @@ class TestEmotionFormatCompatibility:
assert identity["entity_id"] == "501"
assert identity["caller_phone"] == "+79990001122"
def test_reporter_prefers_artifact_context_over_record_fields(self):
from reporter.analytics import _normalize_identity
record = MagicMock()
record.uniqueid = "uid-2"
record.source = "bitrix24"
record.direction = "inbound"
record.user_id = "11"
record.entity_type = "CONTACT"
record.entity_id = "77"
record.caller_phone = "+70000000000"
transcript = {
"CALL_ID": "vx-002",
"MESSAGES": [],
"artifact_context": {
"user_id": "42",
"crm_activity_id": "act-002",
"crm_entity_type": "COMPANY",
"crm_entity_id": "888",
"caller_phone": "+79995554433",
"bitrix_fields": {
"PORTAL_USER_ID": "42",
"CRM_ENTITY_TYPE": "COMPANY",
"CRM_ENTITY_ID": "888",
"PHONE_NUMBER": "+79995554433",
},
},
}
identity = _normalize_identity(record, {}, {}, transcript, {})
assert identity["employee_user_id"] == "42"
assert identity["entity_type"] == "COMPANY"
assert identity["entity_id"] == "888"
assert identity["caller_phone"] == "+79995554433"
class TestReporterRepair:
def test_missing_report_detail_detected(self, tmp_path: Path):

View File

@ -71,11 +71,13 @@ class TestConversationArtifact:
assert len(result["recording_sources"]["local_files"]) == 3
assert len(result["recording_sources"]["source_files"]) == 3
assert result["artifact_context"]["crm_entity_type"] == "CONTACT"
assert result["artifact_context"]["crm_entity_type_id"] == 3
assert result["artifact_context"]["crm_entity_id"] == "999"
assert result["artifact_context"]["voice_files"]["has_rx"] is True
assert (
result["artifact_context"]["bitrix_fields"]["CRM_ENTITY_TYPE"] == "CONTACT"
)
assert result["artifact_context"]["bitrix_fields"]["CRM_ENTITY_TYPE_ID"] == 3
def test_unknown_direction_keeps_side_unknown(self, tmp_path: Path):
from analyzer.transcript_format import build_conversation_artifact
@ -160,12 +162,13 @@ class TestConversationArtifact:
== "https://example.invalid/prospect.mp3"
)
assert result["artifact_context"]["crm_entity_type"] == "LEAD"
assert result["artifact_context"]["crm_entity_type_id"] == 1
assert result["artifact_context"]["crm_entity_id"] == "555"
assert result["artifact_context"]["voice_files"]["local_files"][0]["name"] == "audio.mp3"
class TestTranscriptArtifact:
def test_transcript_payload_includes_bitrix_and_voice_context(self, tmp_path: Path):
def test_transcript_payload_does_not_duplicate_artifact_context(self, tmp_path: Path):
from analyzer.transcript_format import build_bitrix_transcript_payload
spool_dir = tmp_path / "spool"
@ -199,8 +202,4 @@ class TestTranscriptArtifact:
result = build_bitrix_transcript_payload(meta, turns, "pyannote")
assert result["artifact_kind"] == "transcript"
assert result["artifact_context"]["crm_activity_id"] == "act-456"
assert result["artifact_context"]["crm_entity_type"] == "DEAL"
assert result["artifact_context"]["crm_entity_id"] == "314"
assert result["artifact_context"]["bitrix_fields"]["CRM_ACTIVITY_ID"] == "act-456"
assert result["artifact_context"]["voice_files"]["local_files"][0]["name"] == "audio.mp3"
assert "artifact_context" not in result