callscope-ai 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+
7
+ # Packaging
8
+ build/
9
+ dist/
10
+ *.egg-info/
11
+ .eggs/
12
+ wheels/
13
+
14
+ # Environnements virtuels
15
+ .venv/
16
+ venv/
17
+ env/
18
+
19
+ # Tests et outils
20
+ .pytest_cache/
21
+ .coverage
22
+ htmlcov/
23
+ .mypy_cache/
24
+ .ruff_cache/
25
+ .tox/
26
+
27
+ # Secrets et configuration locale
28
+ .env
29
+ .env.*
30
+ *.pem
31
+ *.key
32
+
33
+ # Radar : configuration réelle et sorties (seul radar.example.toml est versionné)
34
+ radar.toml
35
+ *.csv
36
+ rapport*.html
37
+
38
+ # Éditeurs et système
39
+ .vscode/
40
+ .idea/
41
+ .DS_Store
42
+ Thumbs.db
43
+ radar-data/
44
+ radar-out/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jérémie
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,28 @@
1
+ # callscope — notes pour Jérémie
2
+
3
+ ## Ce qui a été fait
4
+ - Bibliothèque sans dépendance obligatoire : `transcribe` (faster-whisper, extra `[whisper]`), `diarize`, `sentiment`, `contact_reasons`, `key_moments`, `analyze` (JSON `callscope/1`, format commun pour custovox-mcp et aircall-mcp).
5
+ - CLI `callscope demo` / `callscope analyze <audio|segments.json>`, appel fictif intégré (mode démo sans modèle ni clé).
6
+ - 9 tests, sans réseau ni modèle. Noms `callscope` et `call-scope` libres sur PyPI (vérifié le 20/11/2026).
7
+
8
+ ## Relecture du 20/11/2026
9
+ - Corrigé : les mots-clés étaient cherchés comme sous-chaînes (« downgrade » → panne via « down », « debug » → bug, « explain » → forfait via « plan »). Ils sont maintenant cherchés comme mots entiers.
10
+ - Corrigé : un segment déjà étiqueté par un autre outil (« SPEAKER_00 », sortie pyannote ou Aircall) faisait planter `diarize` ; l'étiquette est gardée dans `original_speaker` et le rôle est deviné.
11
+ - 11 tests ; démo vérifiée (conseiller/client alternés correctement, facturation + résiliation, plainte, menace de départ, promesse).
12
+
13
+ ## Ce qui reste à tester avec de vrais appels
14
+ - `transcribe` n'a **pas** été exécuté ici (pas de modèle ni d'audio) : tester `callscope analyze appel.wav` avec l'extra `whisper` (le modèle est téléchargé au premier lancement).
15
+ - La séparation conseiller/client est une **heuristique** (canaux stéréo si fournis, sinon alternance sur silences + phrases d'accueil). Pas de pyannote : à évaluer sur de vrais enregistrements ; pour du stéréo, passer `channel_roles` (les segments doivent porter un champ `channel`, que `transcribe` ne remplit pas encore).
16
+ - Sentiment et motifs par mots-clés FR/EN : bases simples, à comparer à un jugement humain avant de s'y fier. Les lexiques sont dans `lexicon.py`.
17
+
18
+ ## Points de vigilance
19
+ - Les enregistrements d'appels contiennent des données personnelles : rien n'est envoyé hors de la machine, mais ne pas versionner d'audio.
20
+ - Les projets suivants doivent réutiliser le format `callscope/1` tel quel.
21
+
22
+ ## Publication (après relecture)
23
+ ```
24
+ cd projets/callscope && python -m build && twine upload dist/*
25
+ ```
26
+
27
+ ## Nom PyPI
28
+ PyPI a refusé `callscope` (400) : trop proche de `caliscope` (calibrage de caméras), car PyPI confond l/i et o/0. Publié sous **`callscope-ai`** ; on importe toujours `callscope`, et les commandes `callscope` et `callscope-ai` font la même chose.
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.5
2
+ Name: callscope-ai
3
+ Version: 0.1.0
4
+ Summary: Local call-center call analysis: transcript, speakers, sentiment, contact reasons and key moments in one JSON.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: call-center,customer-service,sentiment,speech,transcription
8
+ Classifier: Environment :: Console
9
+ Classifier: Programming Language :: Python :: 3
10
+ Requires-Python: >=3.10
11
+ Provides-Extra: test
12
+ Requires-Dist: pytest; extra == 'test'
13
+ Provides-Extra: whisper
14
+ Requires-Dist: faster-whisper>=1.0; extra == 'whisper'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # callscope
18
+
19
+ Analyze customer-service calls locally: timestamped transcript, who speaks when, sentiment curve, contact reasons and key moments, in one JSON.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install callscope-ai # analysis of transcripts (no dependencies)
25
+ pip install "callscope-ai[whisper]" # + local transcription of audio (faster-whisper)
26
+ ```
27
+
28
+ ## Use
29
+
30
+ ```python
31
+ import callscope
32
+
33
+ result = callscope.analyze("call.wav") # audio -> full analysis
34
+ result = callscope.analyze([{"start": 0, "end": 3, "text": "Bonjour, comment puis-je vous aider ?"}])
35
+ ```
36
+
37
+ ```bash
38
+ callscope demo # fictional call, no audio, no model
39
+ callscope analyze call.wav --model small
40
+ callscope analyze segments.json
41
+ ```
42
+
43
+ French and English keyword lexicons are built in; everything runs on your machine.
44
+
45
+ ## Functions
46
+
47
+ | Function | Returns |
48
+ |---|---|
49
+ | `transcribe(path, model_size, language)` | `[{start, end, text}]` (needs the `whisper` extra) |
50
+ | `diarize(segments, channel_roles=None)` | segments with `speaker` = `agent` or `customer` (stereo channels, else turn-taking heuristic) |
51
+ | `sentiment(segments)` | per-segment score (-1..1), customer curve, mean and trend |
52
+ | `contact_reasons(segments)` | ranked reasons: billing, cancellation, outage, delivery, technical_support, subscription_change |
53
+ | `key_moments(segments)` | complaints, churn threats, agent promises |
54
+ | `analyze(source)` | everything above in one dict |
55
+
56
+ ## Output format (`callscope/1`)
57
+
58
+ `analyze()` returns `{schema, source, duration, segments, sentiment, contact_reasons, key_moments}`. This is the shared format for tools built on callscope.
59
+
60
+ ## Limits
61
+
62
+ Lexicon-based sentiment and heuristic speaker separation are simple baselines, not state-of-the-art models.
63
+
64
+ MIT licensed. Run tests with `pip install -e ".[test]" && pytest` (no network).
@@ -0,0 +1,48 @@
1
+ # callscope
2
+
3
+ Analyze customer-service calls locally: timestamped transcript, who speaks when, sentiment curve, contact reasons and key moments, in one JSON.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install callscope-ai # analysis of transcripts (no dependencies)
9
+ pip install "callscope-ai[whisper]" # + local transcription of audio (faster-whisper)
10
+ ```
11
+
12
+ ## Use
13
+
14
+ ```python
15
+ import callscope
16
+
17
+ result = callscope.analyze("call.wav") # audio -> full analysis
18
+ result = callscope.analyze([{"start": 0, "end": 3, "text": "Bonjour, comment puis-je vous aider ?"}])
19
+ ```
20
+
21
+ ```bash
22
+ callscope demo # fictional call, no audio, no model
23
+ callscope analyze call.wav --model small
24
+ callscope analyze segments.json
25
+ ```
26
+
27
+ French and English keyword lexicons are built in; everything runs on your machine.
28
+
29
+ ## Functions
30
+
31
+ | Function | Returns |
32
+ |---|---|
33
+ | `transcribe(path, model_size, language)` | `[{start, end, text}]` (needs the `whisper` extra) |
34
+ | `diarize(segments, channel_roles=None)` | segments with `speaker` = `agent` or `customer` (stereo channels, else turn-taking heuristic) |
35
+ | `sentiment(segments)` | per-segment score (-1..1), customer curve, mean and trend |
36
+ | `contact_reasons(segments)` | ranked reasons: billing, cancellation, outage, delivery, technical_support, subscription_change |
37
+ | `key_moments(segments)` | complaints, churn threats, agent promises |
38
+ | `analyze(source)` | everything above in one dict |
39
+
40
+ ## Output format (`callscope/1`)
41
+
42
+ `analyze()` returns `{schema, source, duration, segments, sentiment, contact_reasons, key_moments}`. This is the shared format for tools built on callscope.
43
+
44
+ ## Limits
45
+
46
+ Lexicon-based sentiment and heuristic speaker separation are simple baselines, not state-of-the-art models.
47
+
48
+ MIT licensed. Run tests with `pip install -e ".[test]" && pytest` (no network).
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "callscope-ai"
7
+ version = "0.1.0"
8
+ description = "Local call-center call analysis: transcript, speakers, sentiment, contact reasons and key moments in one JSON."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = []
14
+ keywords = ["call-center", "speech", "sentiment", "customer-service", "transcription"]
15
+ classifiers = ["Programming Language :: Python :: 3", "Environment :: Console"]
16
+
17
+ [project.optional-dependencies]
18
+ whisper = ["faster-whisper>=1.0"]
19
+ test = ["pytest"]
20
+
21
+ [project.scripts]
22
+ callscope = "callscope.cli:main"
23
+ callscope-ai = "callscope.cli:main"
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["src/callscope"]
27
+
28
+ [tool.hatch.build.targets.sdist]
29
+ include = ["src", "tests", "README.md", "LICENSE", "NOTES-FR.md"]
30
+
31
+ [tool.pytest.ini_options]
32
+ testpaths = ["tests"]
@@ -0,0 +1,9 @@
1
+ """callscope: local analysis of customer-service calls."""
2
+
3
+ from .analysis import analyze, contact_reasons, key_moments, sentiment
4
+ from .diarize import diarize
5
+ from .transcribe import transcribe
6
+
7
+ __version__ = "0.1.0"
8
+ SCHEMA = "callscope/1"
9
+ __all__ = ["analyze", "contact_reasons", "diarize", "key_moments", "sentiment", "transcribe", "SCHEMA"]
@@ -0,0 +1,100 @@
1
+ """Sentiment, contact reasons, key moments and the one-shot ``analyze``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from .diarize import diarize
8
+ from .lexicon import MOMENTS, NEGATIVE, NEGATORS, POSITIVE, REASONS
9
+
10
+ SCHEMA = "callscope/1"
11
+ _WORD = re.compile(r"[\w'’-]+", re.UNICODE)
12
+
13
+
14
+ def _words(text: str) -> list[str]:
15
+ return [w.lower() for w in _WORD.findall(text)]
16
+
17
+
18
+ def _score(text: str) -> float:
19
+ words = _words(text)
20
+ score = 0
21
+ for i, w in enumerate(words):
22
+ sign = 1 if w in POSITIVE else -1 if w in NEGATIVE else 0
23
+ if sign and any(p in NEGATORS for p in words[max(0, i - 2):i]):
24
+ sign = -sign
25
+ score += sign
26
+ return max(-1.0, min(1.0, score / 3))
27
+
28
+
29
+ def _has(text: str, keyword: str) -> bool:
30
+ """Whole-word match, so 'down' does not match 'downgrade' nor 'bug' 'debug'."""
31
+ return re.search(r"(?<![\w])" + re.escape(keyword) + r"(?![\w])", text) is not None
32
+
33
+
34
+ def _label(score: float) -> str:
35
+ return "positive" if score > 0.15 else "negative" if score < -0.15 else "neutral"
36
+
37
+
38
+ def sentiment(segments: list[dict]) -> dict:
39
+ """Sentiment per segment (-1..1) plus the customer's curve over the call."""
40
+ per = [{"index": i, "start": s["start"], "speaker": s.get("speaker"), "score": round(_score(s["text"]), 2),
41
+ "label": _label(_score(s["text"]))} for i, s in enumerate(segments)]
42
+ cust = [p for p in per if p["speaker"] == "customer"] or per
43
+ curve = [{"start": p["start"], "score": p["score"]} for p in cust]
44
+ mean = round(sum(p["score"] for p in cust) / len(cust), 2) if cust else 0.0
45
+ half = len(cust) // 2
46
+ trend = 0.0
47
+ if half:
48
+ trend = round(sum(p["score"] for p in cust[half:]) / (len(cust) - half) - sum(p["score"] for p in cust[:half]) / half, 2)
49
+ return {"segments": per, "customer_curve": curve, "customer_mean": mean, "customer_trend": trend}
50
+
51
+
52
+ def contact_reasons(segments: list[dict]) -> list[dict]:
53
+ """Ranked contact reasons, from the customer's words (all speakers if unlabelled)."""
54
+ cust = [s for s in segments if s.get("speaker") == "customer"] or segments
55
+ text = " ".join(s["text"].lower() for s in cust)
56
+ found = []
57
+ for reason, kws in REASONS.items():
58
+ hits = sorted({k for k in kws if _has(text, k)})
59
+ if hits:
60
+ found.append({"reason": reason, "matches": hits, "score": len(hits)})
61
+ return sorted(found, key=lambda r: (-r["score"], r["reason"]))
62
+
63
+
64
+ def key_moments(segments: list[dict]) -> list[dict]:
65
+ """Complaints and churn threats (customer), promises (agent)."""
66
+ owner = {"complaint": "customer", "churn_threat": "customer", "agent_promise": "agent"}
67
+ out = []
68
+ for i, s in enumerate(segments):
69
+ low = s["text"].lower()
70
+ for kind, kws in MOMENTS.items():
71
+ if s.get("speaker") not in (None, owner[kind]):
72
+ continue
73
+ hit = next((k for k in kws if _has(low, k)), None)
74
+ if hit:
75
+ out.append({"type": kind, "segment": i, "start": s["start"], "speaker": s.get("speaker"),
76
+ "text": s["text"], "match": hit})
77
+ return out
78
+
79
+
80
+ def analyze(source, **transcribe_options) -> dict:
81
+ """Run everything. ``source`` is an audio path or a list of segments.
82
+
83
+ The returned dict is the common callscope format (``schema`` = ``callscope/1``).
84
+ """
85
+ if isinstance(source, str) or hasattr(source, "__fspath__"):
86
+ from .transcribe import transcribe
87
+ segments = transcribe(str(source), **transcribe_options)
88
+ origin = str(source)
89
+ else:
90
+ segments, origin = list(source), None
91
+ segments = diarize(segments)
92
+ return {
93
+ "schema": SCHEMA,
94
+ "source": origin,
95
+ "duration": max((s["end"] for s in segments), default=0.0),
96
+ "segments": segments,
97
+ "sentiment": sentiment(segments),
98
+ "contact_reasons": contact_reasons(segments),
99
+ "key_moments": key_moments(segments),
100
+ }
@@ -0,0 +1,31 @@
1
+ import argparse
2
+ import json
3
+ import sys
4
+
5
+ from . import analyze
6
+ from .demo import DEMO_SEGMENTS
7
+
8
+
9
+ def main(argv=None) -> int:
10
+ p = argparse.ArgumentParser(prog="callscope", description="Analyze a customer-service call locally.")
11
+ sub = p.add_subparsers(dest="cmd", required=True)
12
+ a = sub.add_parser("analyze", help="audio file, or a JSON file of segments")
13
+ a.add_argument("path")
14
+ a.add_argument("--model", default="small", help="faster-whisper model size (audio only)")
15
+ a.add_argument("--language", default=None)
16
+ sub.add_parser("demo", help="analyze a fictional call, no audio or model needed")
17
+ args = p.parse_args(argv)
18
+ if args.cmd == "demo":
19
+ result = analyze(DEMO_SEGMENTS)
20
+ elif args.path.endswith(".json"):
21
+ with open(args.path, encoding="utf-8") as f:
22
+ result = analyze(json.load(f))
23
+ else:
24
+ result = analyze(args.path, model_size=args.model, language=args.language)
25
+ json.dump(result, sys.stdout, ensure_ascii=False, indent=2)
26
+ print()
27
+ return 0
28
+
29
+
30
+ if __name__ == "__main__":
31
+ raise SystemExit(main())
@@ -0,0 +1,10 @@
1
+ """A fictional call (no real recording)."""
2
+
3
+ DEMO_SEGMENTS = [
4
+ {"start": 0.0, "end": 4.0, "text": "Bonjour, vous parlez à Camille, comment puis-je vous aider ?"},
5
+ {"start": 5.5, "end": 12.0, "text": "Bonjour, j'ai un problème avec ma facture, on m'a prélevé deux fois ce mois-ci, c'est inadmissible."},
6
+ {"start": 12.5, "end": 16.0, "text": "Je suis désolée, je vais vérifier tout de suite votre dossier."},
7
+ {"start": 18.0, "end": 24.0, "text": "J'en ai marre, c'est la deuxième fois. Si ça continue je vais résilier et changer d'opérateur."},
8
+ {"start": 24.5, "end": 31.0, "text": "Je comprends. Je m'engage à vous rembourser, et je vous rappelle avant demain pour confirmer."},
9
+ {"start": 33.0, "end": 36.0, "text": "D'accord, merci, c'est très bien."},
10
+ ]
@@ -0,0 +1,51 @@
1
+ """Who speaks when: ``agent`` or ``customer``.
2
+
3
+ Heuristic and fully local. Priority: an existing ``speaker``/``channel`` field
4
+ on the segment, then turn-taking on silence gaps with opening-phrase cues.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ AGENT_CUES = re.compile(
12
+ r"(vous parlez à|comment puis-je|puis-je vous aider|je vais (vérifier|regarder|noter)|"
13
+ r"how can i help|you('re| are) speaking with|let me (check|look))",
14
+ re.I,
15
+ )
16
+ ROLES = ("agent", "customer")
17
+
18
+
19
+ def diarize(segments: list[dict], channel_roles: dict[int, str] | None = None, gap: float = 0.4) -> list[dict]:
20
+ """Return new segments with a ``speaker`` of ``agent`` or ``customer``.
21
+
22
+ ``channel_roles`` maps a stereo channel number to a role, e.g. ``{0: "agent", 1: "customer"}``.
23
+ """
24
+ out = [dict(s) for s in segments]
25
+ for s in out:
26
+ # Labels from other tools (e.g. "SPEAKER_00") are not roles: guess them.
27
+ if "speaker" in s and s["speaker"] not in ROLES:
28
+ s["original_speaker"] = s.pop("speaker")
29
+ if s.get("speaker") in ROLES:
30
+ continue
31
+ if channel_roles and s.get("channel") in channel_roles:
32
+ s["speaker"] = channel_roles[s["channel"]]
33
+ current = 0 # index into ROLES for the running turn
34
+ first = next((s for s in out if "speaker" not in s), None)
35
+ if first is not None and AGENT_CUES.search(first["text"]):
36
+ current = 0
37
+ elif first is not None:
38
+ current = 1
39
+ prev_end = None
40
+ for s in out:
41
+ if "speaker" in s:
42
+ current = ROLES.index(s["speaker"])
43
+ prev_end = s["end"]
44
+ continue
45
+ if prev_end is not None and s["start"] - prev_end >= gap and not AGENT_CUES.search(s["text"]):
46
+ current = 1 - current
47
+ elif AGENT_CUES.search(s["text"]):
48
+ current = 0
49
+ s["speaker"] = ROLES[current]
50
+ prev_end = s["end"]
51
+ return out
@@ -0,0 +1,27 @@
1
+ """Small bilingual (FR/EN) lexicons. Deliberately simple and inspectable."""
2
+
3
+ POSITIVE = {
4
+ "merci", "parfait", "super", "génial", "excellent", "content", "satisfait", "ravi", "bien", "top",
5
+ "thanks", "thank", "great", "perfect", "happy", "excellent", "good", "appreciate",
6
+ }
7
+ NEGATIVE = {
8
+ "inadmissible", "scandaleux", "nul", "énervé", "enervé", "marre", "problème", "probleme", "panne", "arnaque",
9
+ "inacceptable", "déçu", "decu", "plainte", "honteux", "catastrophe", "impossible", "attends",
10
+ "terrible", "angry", "unacceptable", "ridiculous", "broken", "worst", "furious", "disappointed", "complaint",
11
+ }
12
+ NEGATORS = {"pas", "jamais", "ne", "not", "never", "no"}
13
+
14
+ REASONS = {
15
+ "billing": ["facture", "facturation", "prélèvement", "prelevement", "remboursement", "tarif", "invoice", "bill", "refund", "charged"],
16
+ "cancellation": ["résilier", "resilier", "résiliation", "resiliation", "annuler", "cancel", "unsubscribe", "close my account"],
17
+ "outage": ["panne", "coupure", "plus de connexion", "ne marche plus", "ne fonctionne plus", "outage", "not working", "down"],
18
+ "delivery": ["livraison", "colis", "commande", "delivery", "parcel", "order"],
19
+ "technical_support": ["bug", "erreur", "installer", "configurer", "mot de passe", "password", "error", "install"],
20
+ "subscription_change": ["changer d'offre", "forfait", "abonnement", "upgrade", "downgrade", "plan"],
21
+ }
22
+
23
+ MOMENTS = {
24
+ "complaint": ["inadmissible", "scandaleux", "plainte", "inacceptable", "honteux", "complaint", "unacceptable", "ridiculous"],
25
+ "churn_threat": ["résilier", "resilier", "changer d'opérateur", "changer d'operateur", "je pars", "concurrent", "cancel my", "switch to", "leave you"],
26
+ "agent_promise": ["je vous rappelle", "je m'engage", "je vous promets", "avant demain", "sous 48", "i will call you back", "i promise", "within 48"],
27
+ }
@@ -0,0 +1,14 @@
1
+ """Timestamped transcription with faster-whisper (optional dependency)."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ def transcribe(path: str, model_size: str = "small", language: str | None = None, device: str = "cpu") -> list[dict]:
7
+ """Return segments ``[{"start": s, "end": s, "text": str}]``. Runs locally."""
8
+ try:
9
+ from faster_whisper import WhisperModel
10
+ except ImportError as exc: # pragma: no cover - depends on environment
11
+ raise ImportError("Transcription needs faster-whisper: pip install 'callscope-ai[whisper]'") from exc
12
+ model = WhisperModel(model_size, device=device, compute_type="int8")
13
+ segments, _info = model.transcribe(path, language=language, vad_filter=True)
14
+ return [{"start": round(s.start, 2), "end": round(s.end, 2), "text": s.text.strip()} for s in segments]
@@ -0,0 +1,90 @@
1
+ import json
2
+
3
+ import pytest
4
+
5
+ import callscope
6
+ from callscope import analyze, contact_reasons, diarize, key_moments, sentiment
7
+ from callscope.cli import main
8
+ from callscope.demo import DEMO_SEGMENTS
9
+
10
+
11
+ def test_diarize_alternates_and_agent_first():
12
+ out = diarize(DEMO_SEGMENTS)
13
+ assert [s["speaker"] for s in out] == ["agent", "customer", "agent", "customer", "agent", "customer"]
14
+ assert "speaker" not in DEMO_SEGMENTS[0] # input not mutated
15
+
16
+
17
+ def test_diarize_uses_channels_and_existing_labels():
18
+ segs = [{"start": 0, "end": 1, "text": "x", "channel": 1}, {"start": 1, "end": 2, "text": "y", "channel": 0},
19
+ {"start": 2, "end": 3, "text": "z", "speaker": "agent"}]
20
+ out = diarize(segs, channel_roles={0: "agent", 1: "customer"})
21
+ assert [s["speaker"] for s in out] == ["customer", "agent", "agent"]
22
+
23
+
24
+ def test_sentiment_curve_and_negation():
25
+ segs = diarize(DEMO_SEGMENTS)
26
+ s = sentiment(segs)
27
+ assert s["customer_curve"][0]["score"] < 0
28
+ assert s["customer_curve"][-1]["score"] > 0
29
+ assert s["customer_trend"] > 0
30
+ neg = sentiment([{"start": 0, "end": 1, "text": "ce n'est pas bien", "speaker": "customer"}])
31
+ assert neg["segments"][0]["score"] < 0
32
+
33
+
34
+ def test_contact_reasons():
35
+ reasons = contact_reasons(diarize(DEMO_SEGMENTS))
36
+ assert reasons[0]["reason"] in {"billing", "cancellation"}
37
+ assert {r["reason"] for r in reasons} >= {"billing", "cancellation"}
38
+ assert contact_reasons([{"start": 0, "end": 1, "text": "bonjour"}]) == []
39
+
40
+
41
+ def test_key_moments_ownership():
42
+ moments = key_moments(diarize(DEMO_SEGMENTS))
43
+ kinds = {(m["type"], m["speaker"]) for m in moments}
44
+ assert ("complaint", "customer") in kinds and ("churn_threat", "customer") in kinds
45
+ assert ("agent_promise", "agent") in kinds
46
+
47
+
48
+ def test_analyze_common_format_is_json_serialisable():
49
+ r = analyze(DEMO_SEGMENTS)
50
+ assert r["schema"] == callscope.SCHEMA == "callscope/1"
51
+ assert set(r) == {"schema", "source", "duration", "segments", "sentiment", "contact_reasons", "key_moments"}
52
+ assert r["duration"] == 36.0
53
+ json.dumps(r)
54
+
55
+
56
+ def test_analyze_empty():
57
+ r = analyze([])
58
+ assert r["duration"] == 0.0 and r["key_moments"] == []
59
+
60
+
61
+ def test_transcribe_without_dependency_is_clear(monkeypatch):
62
+ import sys
63
+ monkeypatch.setitem(sys.modules, "faster_whisper", None)
64
+ with pytest.raises(ImportError, match=r"callscope-ai\[whisper\]"):
65
+ callscope.transcribe("x.wav")
66
+
67
+
68
+ def test_cli_demo_and_json(capsys, tmp_path):
69
+ assert main(["demo"]) == 0
70
+ assert json.loads(capsys.readouterr().out)["schema"] == "callscope/1"
71
+ f = tmp_path / "c.json"
72
+ f.write_text(json.dumps(DEMO_SEGMENTS))
73
+ assert main(["analyze", str(f)]) == 0
74
+ assert json.loads(capsys.readouterr().out)["contact_reasons"]
75
+
76
+
77
+ def test_keywords_match_whole_words_only():
78
+ from callscope import contact_reasons
79
+ seg = [{"start": 0, "end": 1, "text": "I want to downgrade, can you explain? I debug code."}]
80
+ reasons = {r["reason"]: r["matches"] for r in contact_reasons(seg)}
81
+ assert "outage" not in reasons and "technical_support" not in reasons
82
+ assert reasons["subscription_change"] == ["downgrade"]
83
+
84
+
85
+ def test_foreign_speaker_labels_do_not_crash():
86
+ from callscope import diarize
87
+ out = diarize([{"start": 0, "end": 1, "text": "Bonjour, comment puis-je vous aider ?", "speaker": "SPEAKER_00"},
88
+ {"start": 2, "end": 3, "text": "J'ai un souci", "speaker": "SPEAKER_01"}])
89
+ assert [s["speaker"] for s in out] == ["agent", "customer"]
90
+ assert out[0]["original_speaker"] == "SPEAKER_00"