PR: добавлена команда подготовки пака документов для передачи в анализ
This commit is contained in:
parent
f34ae97646
commit
84c6287ecd
|
|
@ -23,3 +23,4 @@ spool/*
|
|||
!spool/.gitkeep
|
||||
logs/*
|
||||
!logs/.gitkeep
|
||||
tmp/
|
||||
|
|
|
|||
|
|
@ -0,0 +1,3 @@
|
|||
from .pack import AnalysisPackSummary, build_analysis_pack
|
||||
|
||||
__all__ = ["AnalysisPackSummary", "build_analysis_pack"]
|
||||
|
|
@ -0,0 +1,511 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from io import StringIO
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable, Mapping
|
||||
import csv
|
||||
import json
|
||||
import re
|
||||
|
||||
|
||||
CALL_CATEGORY_ENUM = ("sale", "complaint", "client_support", "marketing_event", "other")
|
||||
RISK_LEVEL_ENUM = ("low", "medium", "high", "critical", "unknown")
|
||||
|
||||
ANALYSIS_FIELDS = (
|
||||
"call_category",
|
||||
"conversation_summary",
|
||||
"client_intent",
|
||||
"sentiment",
|
||||
"relationship_risk_level",
|
||||
"next_contact_date",
|
||||
"manager_readiness",
|
||||
"client_expectations",
|
||||
"objections",
|
||||
"client_segment",
|
||||
"company_perception",
|
||||
"recommendations",
|
||||
"requires_attention",
|
||||
"evidence_quotes",
|
||||
)
|
||||
|
||||
CSV_COLUMNS = (
|
||||
"audio_file_id",
|
||||
"source_file_name",
|
||||
"source_file_path",
|
||||
"source_direction",
|
||||
"call_date",
|
||||
"call_time",
|
||||
"manager",
|
||||
"client_phone",
|
||||
"manager_phone",
|
||||
"duration_seconds",
|
||||
"language",
|
||||
"quality_score",
|
||||
"current_categories",
|
||||
"word_count",
|
||||
"segment_count",
|
||||
"is_empty_transcript",
|
||||
"is_short_transcript",
|
||||
"is_suspicious_language",
|
||||
"preliminary_attention_flags",
|
||||
"scorecard_flags",
|
||||
"transcript_text",
|
||||
*ANALYSIS_FIELDS,
|
||||
)
|
||||
|
||||
COMPLAINT_MARKER_PATTERNS = (
|
||||
r"\bжалоб\w*",
|
||||
r"\bпретенз\w*",
|
||||
r"\bнедовол\w*",
|
||||
r"\bпроблем\w*",
|
||||
r"\bотказ\w*",
|
||||
r"\bдорого\b",
|
||||
r"\bне\s+устраивает\b",
|
||||
r"\bверн(?:уть|ите|ем)\w*",
|
||||
r"\bобман\w*",
|
||||
r"\bплохо\b",
|
||||
r"\bзадерж\w*",
|
||||
)
|
||||
|
||||
|
||||
def _utc_now() -> str:
|
||||
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
|
||||
|
||||
|
||||
def _as_mapping(value: Any) -> dict[str, Any]:
|
||||
return dict(value) if isinstance(value, Mapping) else {}
|
||||
|
||||
|
||||
def _as_list(value: Any) -> list[Any]:
|
||||
return list(value) if isinstance(value, list) else []
|
||||
|
||||
|
||||
def _load_json(path: Path) -> dict[str, Any]:
|
||||
with path.open("r", encoding="utf-8") as handle:
|
||||
loaded = json.load(handle)
|
||||
if not isinstance(loaded, Mapping):
|
||||
raise ValueError(f"expected JSON object in {path}")
|
||||
return dict(loaded)
|
||||
|
||||
|
||||
def _parse_source_filename(file_name: str) -> dict[str, str]:
|
||||
stem = Path(file_name).stem
|
||||
parts = stem.split("_")
|
||||
parsed = {
|
||||
"call_date": "",
|
||||
"call_time": "",
|
||||
"manager": "",
|
||||
"client_phone": "",
|
||||
"manager_phone": "",
|
||||
"direction_marker": "",
|
||||
}
|
||||
if len(parts) >= 1:
|
||||
parsed["call_date"] = parts[0]
|
||||
if len(parts) >= 2:
|
||||
parsed["call_time"] = parts[1].replace("-", ":")
|
||||
if len(parts) >= 3:
|
||||
parsed["manager"] = parts[2]
|
||||
|
||||
phones = [part for part in parts if re.fullmatch(r"\+?\d{5,}", part)]
|
||||
if phones:
|
||||
parsed["client_phone"] = phones[0]
|
||||
if len(phones) > 1:
|
||||
parsed["manager_phone"] = phones[-1]
|
||||
|
||||
markers = [part for part in parts if part in {"исх", "вх", "out", "in", "outgoing", "incoming"}]
|
||||
if markers:
|
||||
parsed["direction_marker"] = markers[0]
|
||||
return parsed
|
||||
|
||||
|
||||
def _check_map(classification: Mapping[str, Any]) -> dict[str, dict[str, Any]]:
|
||||
checks = _as_list(classification.get("checks"))
|
||||
return {
|
||||
str(item.get("id")): dict(item)
|
||||
for item in checks
|
||||
if isinstance(item, Mapping) and item.get("id")
|
||||
}
|
||||
|
||||
|
||||
def _count_words(text: str) -> int:
|
||||
return len([token for token in text.split() if token.strip()])
|
||||
|
||||
|
||||
def _matching_markers(text: str) -> list[str]:
|
||||
matches: list[str] = []
|
||||
for pattern in COMPLAINT_MARKER_PATTERNS:
|
||||
match = re.search(pattern, text, flags=re.IGNORECASE)
|
||||
if match:
|
||||
matches.append(match.group(0))
|
||||
return matches
|
||||
|
||||
|
||||
def _scorecard_flags(classification: Mapping[str, Any]) -> list[str]:
|
||||
checks = _check_map(classification)
|
||||
flags: list[str] = []
|
||||
for check_id, check in sorted(checks.items()):
|
||||
if check.get("passed") is False:
|
||||
flags.append(check_id)
|
||||
return flags
|
||||
|
||||
|
||||
def _attention_flags(
|
||||
*,
|
||||
categories: list[str],
|
||||
classification: Mapping[str, Any],
|
||||
language: str,
|
||||
quality_score: int,
|
||||
word_count: int,
|
||||
transcript_text: str,
|
||||
) -> list[str]:
|
||||
checks = _check_map(classification)
|
||||
flags: list[str] = []
|
||||
|
||||
negative_check = checks.get("negative_tone", {})
|
||||
if "negative_tone" in categories or negative_check.get("passed") is False:
|
||||
flags.append("negative_tone_scorecard")
|
||||
|
||||
next_step_check = checks.get("next_step", {})
|
||||
if "next_step_present" not in categories or next_step_check.get("passed") is False:
|
||||
flags.append("missing_next_step")
|
||||
|
||||
if "too_short" in categories or "low_content" in categories or word_count < 8:
|
||||
flags.append("short_or_low_content")
|
||||
|
||||
if quality_score < 60 or "low_quality" in categories:
|
||||
flags.append("low_quality")
|
||||
|
||||
if language and language != "ru":
|
||||
flags.append("suspicious_language")
|
||||
|
||||
markers = _matching_markers(transcript_text)
|
||||
if markers:
|
||||
flags.append("complaint_markers:" + ",".join(dict.fromkeys(markers)))
|
||||
|
||||
return flags
|
||||
|
||||
|
||||
def expected_output_schema() -> dict[str, Any]:
|
||||
return {
|
||||
"type": "object",
|
||||
"required": list(ANALYSIS_FIELDS),
|
||||
"properties": {
|
||||
"call_category": {"type": "string", "enum": list(CALL_CATEGORY_ENUM)},
|
||||
"conversation_summary": {"type": "string"},
|
||||
"client_intent": {"type": "string"},
|
||||
"sentiment": {"type": "string", "enum": ["positive", "neutral", "negative", "mixed", "unknown"]},
|
||||
"relationship_risk_level": {"type": "string", "enum": list(RISK_LEVEL_ENUM)},
|
||||
"next_contact_date": {
|
||||
"type": ["string", "null"],
|
||||
"description": "ISO date if stated in the transcript, otherwise null.",
|
||||
},
|
||||
"manager_readiness": {
|
||||
"type": "string",
|
||||
"enum": ["high", "medium", "low", "unknown"],
|
||||
},
|
||||
"client_expectations": {"type": "array", "items": {"type": "string"}},
|
||||
"objections": {"type": "array", "items": {"type": "string"}},
|
||||
"client_segment": {"type": "string"},
|
||||
"company_perception": {"type": "string"},
|
||||
"recommendations": {"type": "array", "items": {"type": "string"}},
|
||||
"requires_attention": {"type": "boolean"},
|
||||
"evidence_quotes": {"type": "array", "items": {"type": "string"}},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _build_call_prompt(call: Mapping[str, Any]) -> str:
|
||||
return "\n".join(
|
||||
[
|
||||
"Проанализируй один телефонный разговор по транскрипции.",
|
||||
"Верни только JSON по expected_output_schema.",
|
||||
f"ID звонка: {call['audio_file_id']}",
|
||||
f"Менеджер: {call['manager'] or 'unknown'}",
|
||||
f"Направление: {call['source_direction'] or 'unknown'}",
|
||||
f"Предварительные флаги внимания: {', '.join(call['preliminary_attention_flags']) or 'none'}",
|
||||
"Транскрипция:",
|
||||
str(call["transcript_text"]),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def _build_aggregate_prompt() -> str:
|
||||
return "\n".join(
|
||||
[
|
||||
"Проанализируй массив calls из analysis_pack.json.",
|
||||
"Сформируй агрегированный отчет по всем звонкам:",
|
||||
"- количественные показатели по отдельным менеджерам;",
|
||||
"- ранжирование ожиданий и запросов клиентов;",
|
||||
"- сводные оценки и тренды взаимодействий с клиентами в разрезе категорий звонков;",
|
||||
"- распределение готовности менеджеров к переговорам;",
|
||||
"- карту возражений;",
|
||||
"- профилирование клиентов по сегментам;",
|
||||
"- описание того, как компания выглядит в глазах клиентов;",
|
||||
"- рекомендации и мероприятия по устранению недостатков;",
|
||||
"- перечень звонков, требующих внимания.",
|
||||
"Используй только факты из транскрипций и evidence_quotes из анализа отдельных звонков.",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def _extract_call(payload: Mapping[str, Any]) -> dict[str, Any]:
|
||||
source_file = _as_mapping(payload.get("source_file"))
|
||||
transcription = _as_mapping(payload.get("transcription"))
|
||||
classification = _as_mapping(payload.get("classification"))
|
||||
categories = [str(item) for item in _as_list(classification.get("categories"))]
|
||||
file_name = str(source_file.get("name") or Path(str(source_file.get("path", ""))).name)
|
||||
parsed_name = _parse_source_filename(file_name)
|
||||
transcript_text = str(transcription.get("text") or "")
|
||||
segments = [
|
||||
dict(item) if isinstance(item, Mapping) else {"value": item}
|
||||
for item in _as_list(transcription.get("segments"))
|
||||
]
|
||||
language = str(transcription.get("language") or "")
|
||||
quality_score = int(classification.get("quality_score") or 0)
|
||||
word_count = _count_words(transcript_text)
|
||||
flags = _attention_flags(
|
||||
categories=categories,
|
||||
classification=classification,
|
||||
language=language,
|
||||
quality_score=quality_score,
|
||||
word_count=word_count,
|
||||
transcript_text=transcript_text,
|
||||
)
|
||||
|
||||
call: dict[str, Any] = {
|
||||
"audio_file_id": int(payload.get("audio_file_id") or 0),
|
||||
"source_type": str(payload.get("source_type") or ""),
|
||||
"source_id": str(payload.get("source_id") or ""),
|
||||
"source_direction": str(payload.get("source_direction") or source_file.get("direction") or ""),
|
||||
"source_file_name": file_name,
|
||||
"source_file_path": str(source_file.get("path") or ""),
|
||||
"call_date": parsed_name["call_date"],
|
||||
"call_time": parsed_name["call_time"],
|
||||
"manager": parsed_name["manager"],
|
||||
"client_phone": parsed_name["client_phone"],
|
||||
"manager_phone": parsed_name["manager_phone"],
|
||||
"duration_seconds": transcription.get("duration_seconds") or source_file.get("duration_seconds") or "",
|
||||
"language": language,
|
||||
"quality_score": quality_score,
|
||||
"current_categories": categories,
|
||||
"scorecard_checks": _as_list(classification.get("checks")),
|
||||
"scorecard_flags": _scorecard_flags(classification),
|
||||
"word_count": word_count,
|
||||
"segment_count": len(segments),
|
||||
"is_empty_transcript": not bool(transcript_text.strip()),
|
||||
"is_short_transcript": word_count < 8,
|
||||
"is_suspicious_language": bool(language and language != "ru"),
|
||||
"preliminary_attention_flags": flags,
|
||||
"transcript_text": transcript_text,
|
||||
"segments": segments,
|
||||
"analysis_targets": {field: "" for field in ANALYSIS_FIELDS},
|
||||
"expected_output_schema": expected_output_schema(),
|
||||
}
|
||||
call["analysis_prompt"] = _build_call_prompt(call)
|
||||
return call
|
||||
|
||||
|
||||
def _manager_distribution(calls: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:
|
||||
counter = Counter(str(call.get("manager") or "unknown") for call in calls)
|
||||
return [{"manager": manager, "call_count": count} for manager, count in counter.most_common()]
|
||||
|
||||
|
||||
def _category_distribution(calls: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:
|
||||
counter: Counter[str] = Counter()
|
||||
for call in calls:
|
||||
counter.update(str(item) for item in _as_list(call.get("current_categories")))
|
||||
return [{"category": category, "call_count": count} for category, count in counter.most_common()]
|
||||
|
||||
|
||||
def _language_distribution(calls: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:
|
||||
counter = Counter(str(call.get("language") or "unknown") for call in calls)
|
||||
return [{"language": language, "call_count": count} for language, count in counter.most_common()]
|
||||
|
||||
|
||||
def _build_pack(calls: list[dict[str, Any]], *, source_dir: Path) -> dict[str, Any]:
|
||||
total_duration = sum(float(call.get("duration_seconds") or 0) for call in calls)
|
||||
calls_requiring_preliminary_attention = [
|
||||
call["audio_file_id"] for call in calls if call.get("preliminary_attention_flags")
|
||||
]
|
||||
return {
|
||||
"metadata": {
|
||||
"artifact_type": "analysis_prompt_pack",
|
||||
"artifact_version": 1,
|
||||
"mode": "prompt-pack-only",
|
||||
"created_at": _utc_now(),
|
||||
"source_dir": str(source_dir.resolve()),
|
||||
"call_count": len(calls),
|
||||
"empty_transcript_count": sum(1 for call in calls if call.get("is_empty_transcript")),
|
||||
"total_duration_minutes": round(total_duration / 60, 2),
|
||||
"call_category_enum": list(CALL_CATEGORY_ENUM),
|
||||
"relationship_risk_level_enum": list(RISK_LEVEL_ENUM),
|
||||
},
|
||||
"expected_output_schema": expected_output_schema(),
|
||||
"prompt_templates": {
|
||||
"single_call": (
|
||||
"Проанализируй один телефонный разговор по транскрипции и верни только JSON "
|
||||
"по expected_output_schema."
|
||||
),
|
||||
"aggregate": _build_aggregate_prompt(),
|
||||
},
|
||||
"aggregation_inputs": {
|
||||
"manager_distribution": _manager_distribution(calls),
|
||||
"current_category_distribution": _category_distribution(calls),
|
||||
"language_distribution": _language_distribution(calls),
|
||||
"calls_requiring_preliminary_attention": calls_requiring_preliminary_attention,
|
||||
"analysis_tasks": [
|
||||
"quantitative_manager_metrics",
|
||||
"client_expectation_ranking",
|
||||
"category_trends",
|
||||
"manager_readiness_distribution",
|
||||
"objection_map",
|
||||
"client_segmentation",
|
||||
"company_perception",
|
||||
"improvement_recommendations",
|
||||
"attention_call_list",
|
||||
],
|
||||
},
|
||||
"calls": calls,
|
||||
}
|
||||
|
||||
|
||||
def _csv_value(value: Any) -> Any:
|
||||
if isinstance(value, (list, tuple)):
|
||||
return ";".join(str(item) for item in value)
|
||||
if isinstance(value, dict):
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True)
|
||||
return value
|
||||
|
||||
|
||||
def _render_csv(calls: list[Mapping[str, Any]]) -> str:
|
||||
buffer = StringIO()
|
||||
writer = csv.DictWriter(buffer, fieldnames=list(CSV_COLUMNS), extrasaction="ignore")
|
||||
writer.writeheader()
|
||||
for call in calls:
|
||||
row = {column: _csv_value(call.get(column, "")) for column in CSV_COLUMNS}
|
||||
targets = _as_mapping(call.get("analysis_targets"))
|
||||
for field in ANALYSIS_FIELDS:
|
||||
row[field] = targets.get(field, "")
|
||||
writer.writerow(row)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _format_bool(value: Any) -> str:
|
||||
return "yes" if value else "no"
|
||||
|
||||
|
||||
def _render_markdown(pack: Mapping[str, Any]) -> str:
|
||||
metadata = _as_mapping(pack.get("metadata"))
|
||||
aggregation = _as_mapping(pack.get("aggregation_inputs"))
|
||||
calls = [
|
||||
dict(item) if isinstance(item, Mapping) else {}
|
||||
for item in _as_list(pack.get("calls"))
|
||||
]
|
||||
lines: list[str] = [
|
||||
"# Материал для дальнейшего анализа звонков",
|
||||
"",
|
||||
"## Инструкция",
|
||||
"Материал подготовлен в режиме prompt-pack-only. Семантические поля не заполнены автоматически: используйте prompt и expected_output_schema для последующего анализа.",
|
||||
"",
|
||||
"## Сводка набора",
|
||||
f"- Звонков: {metadata.get('call_count', 0)}",
|
||||
f"- Пустых транскрипций: {metadata.get('empty_transcript_count', 0)}",
|
||||
f"- Суммарная длительность, минут: {metadata.get('total_duration_minutes', 0)}",
|
||||
f"- Категории звонков: {', '.join(CALL_CATEGORY_ENUM)}",
|
||||
f"- Уровни риска: {', '.join(RISK_LEVEL_ENUM)}",
|
||||
"",
|
||||
"## Менеджеры",
|
||||
"| Менеджер | Звонков |",
|
||||
"| --- | ---: |",
|
||||
]
|
||||
for item in _as_list(aggregation.get("manager_distribution")):
|
||||
row = _as_mapping(item)
|
||||
lines.append(f"| {row.get('manager', 'unknown')} | {row.get('call_count', 0)} |")
|
||||
|
||||
lines.extend(
|
||||
[
|
||||
"",
|
||||
"## Схема анализа одного звонка",
|
||||
"Ожидаемые поля JSON:",
|
||||
", ".join(ANALYSIS_FIELDS),
|
||||
"",
|
||||
"## Агрегированный prompt",
|
||||
str(_as_mapping(pack.get("prompt_templates")).get("aggregate", "")),
|
||||
"",
|
||||
"## Карточки звонков",
|
||||
]
|
||||
)
|
||||
|
||||
for call in calls:
|
||||
flags = _as_list(call.get("preliminary_attention_flags"))
|
||||
lines.extend(
|
||||
[
|
||||
"",
|
||||
f"### Звонок #{call.get('audio_file_id')}",
|
||||
f"- Менеджер: {call.get('manager') or 'unknown'}",
|
||||
f"- Файл: {call.get('source_file_name')}",
|
||||
f"- Дата/время: {call.get('call_date') or '-'} {call.get('call_time') or ''}".rstrip(),
|
||||
f"- Направление: {call.get('source_direction') or 'unknown'}",
|
||||
f"- Длительность, сек: {call.get('duration_seconds') or '-'}",
|
||||
f"- Язык: {call.get('language') or '-'}",
|
||||
f"- Quality score: {call.get('quality_score')}",
|
||||
f"- Текущие категории: {', '.join(_as_list(call.get('current_categories'))) or '-'}",
|
||||
f"- Предварительно требует внимания: {_format_bool(bool(flags))}",
|
||||
f"- Предварительные флаги: {', '.join(str(item) for item in flags) or '-'}",
|
||||
"",
|
||||
"#### Prompt",
|
||||
"```text",
|
||||
str(call.get("analysis_prompt") or ""),
|
||||
"```",
|
||||
"",
|
||||
"#### Транскрипция",
|
||||
str(call.get("transcript_text") or "_Нет текста транскрипции._"),
|
||||
]
|
||||
)
|
||||
|
||||
return "\n".join(lines).rstrip() + "\n"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AnalysisPackSummary:
|
||||
source_dir: Path
|
||||
output_dir: Path
|
||||
call_count: int
|
||||
empty_transcript_count: int
|
||||
json_path: Path
|
||||
csv_path: Path
|
||||
markdown_path: Path
|
||||
|
||||
|
||||
def build_analysis_pack(source_dir: Path, output_dir: Path) -> AnalysisPackSummary:
|
||||
source_dir = Path(source_dir)
|
||||
output_dir = Path(output_dir)
|
||||
json_paths = sorted(source_dir.glob("*.json"))
|
||||
calls = [_extract_call(_load_json(path)) for path in json_paths]
|
||||
calls.sort(key=lambda item: item["audio_file_id"])
|
||||
pack = _build_pack(calls, source_dir=source_dir)
|
||||
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
json_path = output_dir / "analysis_pack.json"
|
||||
csv_path = output_dir / "calls_for_analysis.csv"
|
||||
markdown_path = output_dir / "analysis_prompt_pack.md"
|
||||
|
||||
json_path.write_text(
|
||||
json.dumps(pack, ensure_ascii=False, sort_keys=True, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
csv_path.write_text(_render_csv(calls), encoding="utf-8", newline="")
|
||||
markdown_path.write_text(_render_markdown(pack), encoding="utf-8")
|
||||
|
||||
return AnalysisPackSummary(
|
||||
source_dir=source_dir,
|
||||
output_dir=output_dir,
|
||||
call_count=len(calls),
|
||||
empty_transcript_count=int(pack["metadata"]["empty_transcript_count"]),
|
||||
json_path=json_path,
|
||||
csv_path=csv_path,
|
||||
markdown_path=markdown_path,
|
||||
)
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import csv
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from b24calls.analysis import build_analysis_pack
|
||||
|
||||
|
||||
def _write_export(path: Path, *, audio_file_id: int, language: str = "ru", text: str | None = None) -> None:
|
||||
payload = {
|
||||
"audio_file_id": audio_file_id,
|
||||
"source_type": "local",
|
||||
"source_id": f"outgoing/26-05-2026_13-50-48_Менеджер Тест_+7900000000{audio_file_id}_исх_+79111111111.mp3",
|
||||
"source_direction": "outgoing",
|
||||
"source_file": {
|
||||
"name": f"26-05-2026_13-50-48_Менеджер Тест_+7900000000{audio_file_id}_исх_+79111111111.mp3",
|
||||
"path": f"/tmp/call-{audio_file_id}.mp3",
|
||||
"direction": "outgoing",
|
||||
"duration_seconds": 60.0,
|
||||
},
|
||||
"transcription": {
|
||||
"language": language,
|
||||
"duration_seconds": 60.0,
|
||||
"text": text
|
||||
if text is not None
|
||||
else "Здравствуйте. Клиент говорит, что есть проблема и нужен каталог. Перезвоните завтра.",
|
||||
"segments": [
|
||||
{"index": 0, "start_seconds": 0.0, "end_seconds": 2.0, "text": "Здравствуйте."},
|
||||
{"index": 1, "start_seconds": 2.0, "end_seconds": 4.0, "text": "Есть проблема."},
|
||||
],
|
||||
},
|
||||
"classification": {
|
||||
"quality_score": 85,
|
||||
"categories": ["greeting_present", "need_identified", "negative_tone", "high_quality"],
|
||||
"checks": [
|
||||
{"id": "greeting", "passed": True, "score": 20, "evidence": "Здравствуйте"},
|
||||
{"id": "next_step", "passed": True, "score": 20, "evidence": "завтра"},
|
||||
{"id": "negative_tone", "passed": False, "score": -15, "evidence": "проблема"},
|
||||
],
|
||||
},
|
||||
}
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
class AnalysisPackTests(unittest.TestCase):
|
||||
def test_build_analysis_pack_writes_json_csv_and_markdown(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
root = Path(tmp_dir)
|
||||
source_dir = root / "output" / "exports" / "json"
|
||||
output_dir = root / "output" / "analysis"
|
||||
_write_export(source_dir / "000000002.json", audio_file_id=2, language="en")
|
||||
_write_export(source_dir / "000000001.json", audio_file_id=1)
|
||||
|
||||
summary = build_analysis_pack(source_dir, output_dir)
|
||||
|
||||
self.assertEqual(summary.call_count, 2)
|
||||
self.assertEqual(summary.empty_transcript_count, 0)
|
||||
self.assertTrue(summary.json_path.exists())
|
||||
self.assertTrue(summary.csv_path.exists())
|
||||
self.assertTrue(summary.markdown_path.exists())
|
||||
|
||||
pack = json.loads(summary.json_path.read_text(encoding="utf-8"))
|
||||
self.assertEqual(pack["metadata"]["call_count"], 2)
|
||||
self.assertEqual(pack["metadata"]["mode"], "prompt-pack-only")
|
||||
self.assertIn("aggregate", pack["prompt_templates"])
|
||||
self.assertEqual([call["audio_file_id"] for call in pack["calls"]], [1, 2])
|
||||
for call in pack["calls"]:
|
||||
self.assertIn("manager", call)
|
||||
self.assertIn("transcript_text", call)
|
||||
self.assertIn("analysis_prompt", call)
|
||||
self.assertIn("expected_output_schema", call)
|
||||
|
||||
with summary.csv_path.open("r", encoding="utf-8", newline="") as handle:
|
||||
rows = list(csv.DictReader(handle))
|
||||
self.assertEqual(len(rows), 2)
|
||||
self.assertIn("call_category", rows[0])
|
||||
self.assertEqual(rows[0]["call_category"], "")
|
||||
self.assertIn("negative_tone_scorecard", rows[0]["preliminary_attention_flags"])
|
||||
self.assertIn("suspicious_language", rows[1]["preliminary_attention_flags"])
|
||||
|
||||
markdown = summary.markdown_path.read_text(encoding="utf-8")
|
||||
self.assertIn("## Сводка набора", markdown)
|
||||
self.assertIn("## Менеджеры", markdown)
|
||||
self.assertIn("## Схема анализа одного звонка", markdown)
|
||||
self.assertIn("## Карточки звонков", markdown)
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
unittest.main()
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
from b24calls.analysis import build_analysis_pack
|
||||
|
||||
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description="Build prompt-pack material from exported call JSON artifacts.")
|
||||
parser.add_argument(
|
||||
"--source-dir",
|
||||
type=Path,
|
||||
default=Path("output/exports/json"),
|
||||
help="Directory containing per-call JSON export artifacts.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-dir",
|
||||
type=Path,
|
||||
default=Path("output/analysis"),
|
||||
help="Directory where analysis_pack.json, calls_for_analysis.csv, and analysis_prompt_pack.md will be written.",
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = _build_parser().parse_args()
|
||||
summary = build_analysis_pack(args.source_dir, args.output_dir)
|
||||
print("analysis prompt-pack summary")
|
||||
print(f"source_dir: {summary.source_dir}")
|
||||
print(f"output_dir: {summary.output_dir}")
|
||||
print(f"calls: {summary.call_count}")
|
||||
print(f"empty_transcripts: {summary.empty_transcript_count}")
|
||||
print(f"json: {summary.json_path}")
|
||||
print(f"csv: {summary.csv_path}")
|
||||
print(f"markdown: {summary.markdown_path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Loading…
Reference in New Issue